0% found this document useful (0 votes)
3 views18 pages

7 Marker Java

The document discusses various Java programming concepts including data types (primitive and non-primitive), control structures (decision-making and looping), multithreading, exception handling, and the Java Virtual Machine (JVM) and Java Runtime Environment (JRE). It provides code examples for creating threads, handling exceptions, and using constructors, while explaining key concepts like polymorphism, abstraction, and the differences between checked and unchecked exceptions. Overall, it serves as a comprehensive overview of fundamental Java programming principles and practices.

Uploaded by

SUMIT KOLI
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

7 Marker Java

The document discusses various Java programming concepts including data types (primitive and non-primitive), control structures (decision-making and looping), multithreading, exception handling, and the Java Virtual Machine (JVM) and Java Runtime Environment (JRE). It provides code examples for creating threads, handling exceptions, and using constructors, while explaining key concepts like polymorphism, abstraction, and the differences between checked and unchecked exceptions. Overall, it serves as a comprehensive overview of fundamental Java programming principles and practices.

Uploaded by

SUMIT KOLI
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q1. Discuss the different data types and control structures in Java with examples.

Java provides different data types to store values and control structures to control the flow of a
program.

Data Types in Java

Java data types are mainly divided into Primi ve and Non-Primi ve types.

1. Primi ve Data Types


These are basic built-in types used to store simple values.

 int – stores integers (e.g., int a = 10;)

 float – stores decimal numbers (e.g., float b = 5.5f;)

 double – stores large decimal numbers

 char – stores single characters (e.g., char c = 'A';)

 boolean – stores true or false

 byte, short, long – used for different integer ranges

Example:

class DataTypes {

public sta c void main(String[] args) {

int a = 10;

float b = 5.5f;

char c = 'A';

boolean flag = true;

[Link](a);

[Link](b);

[Link](c);

[Link](flag);

}
2. Non-Primi ve Data Types
These include classes, objects, arrays, and strings.
They are used to store complex data.

Example: String name = "Aryan";

Control Structures in Java

Control structures determine how the program executes statements.

1. Decision Making Statements

 if statement

int x = 10;

if (x > 5) {

[Link]("x is greater than 5");

 if-else statement

int num = 4;

if (num % 2 == 0)

[Link]("Even");

else

[Link]("Odd");

 switch statement

int day = 2;

switch(day) {

case 1: [Link]("Monday"); break;

case 2: [Link]("Tuesday"); break;

2. Looping Statements

 for loop
for(int i = 1; i <= 5; i++) {

[Link](i);

 while loop

int i = 1;

while(i <= 3) {

[Link](i);

i++;

 do-while loop

int j = 1;

do {

[Link](j);

j++;

} while(j <= 3);

Thus, data types define the kind of data stored, while control structures manage the execu on
flow of the program.

Q2. Explain the concept of mul threading. Write a program to implement two threads
prin ng numbers alterna vely.

Mul threading is a feature in Java that allows mul ple threads to execute simultaneously
within a single program.
Each thread performs a separate task, improving program efficiency and performance.

A thread is a lightweight process that shares the same memory space.

Advantages of Mul threading

 Improves CPU u liza on

 Allows concurrent execu on


 Makes programs faster and more responsive

Example Program: Two Threads Prin ng Numbers

class Thread1 extends Thread {

public void run() {

for(int i = 1; i <= 5; i += 2) {

[Link]("Thread 1: " + i);

class Thread2 extends Thread {

public void run() {

for(int i = 2; i <= 6; i += 2) {

[Link]("Thread 2: " + i);

public class TestThread {

public sta c void main(String[] args) {

Thread1 t1 = new Thread1();

Thread2 t2 = new Thread2();

[Link]();

[Link]();

}
}

In this program, two threads run concurrently, each prin ng numbers in sequence.

Q3. Write a Java program to take user input and display the reverse of a string.

import java.u [Link];

class ReverseString {

public sta c void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a string: ");

String str = [Link]();

String rev = "";

for(int i = [Link]() - 1; i >= 0; i--) {

rev = rev + [Link](i);

[Link]("Reversed string: " + rev);

A 10-marker wants a bit of architecture, a bit of mechanism, and a bit of comparison. Think of it
as explaining the machinery inside the Java ecosystem rather than just naming the parts.

Q4. Explain the concept of Java Virtual Machine (JVM) and Java Run me Environment (JRE).
Java was designed around a clever idea: compile once, run anywhere. The trick that makes this
work is the combina on of bytecode, the Java Virtual Machine (JVM), and the Java Run me
Environment (JRE).

Java Virtual Machine (JVM)

The Java Virtual Machine (JVM) is an abstract compu ng machine responsible for execu ng
Java bytecode. When a Java program is compiled, the compiler does not generate machine
code directly. Instead, it produces bytecode (.class files).

Bytecode is pla orm-independent, meaning it can run on any system that has a JVM installed.
The JVM reads this bytecode and converts it into machine-level instruc ons that the opera ng
system and hardware can execute.

This design is what makes Java programs portable across different systems such as Windows,
Linux, and macOS.

Main responsibili es of JVM:

1. Class Loader
The class loader loads compiled .class files into memory when the program starts.

2. Bytecode Verifier
It checks the bytecode to ensure it is safe and follows Java rules. This prevents illegal memory
access and improves security.

3. Interpreter and JIT Compiler


The JVM interprets bytecode line by line or uses the Just-In-Time (JIT) compiler to convert
frequently used bytecode into machine code for faster execu on.

4. Memory Management
The JVM manages memory alloca on and dealloca on using a mechanism called Garbage
Collec on, which automa cally removes unused objects.

Because each opera ng system has its own JVM implementa on, the same Java program can
run on mul ple pla orms without modifica on.

Java Run me Environment (JRE)

The Java Run me Environment (JRE) provides the environment necessary to run Java
programs. It includes the JVM along with standard libraries and suppor ng files required for
program execu on.
In simple terms, if the JVM is the engine, the JRE is the complete running environment that
supplies fuel, tools, and libraries.

Components of JRE:

1. JVM (Java Virtual Machine)


Executes the bytecode and manages program execu on.

2. Java Class Libraries


These libraries contain predefined classes used for tasks such as input/output, networking, data
structures, and u li es.

3. Suppor ng Files
Configura on files and resources required to run Java applica ons.

The JRE allows users to run Java applica ons but not develop them.

Rela onship between JDK, JRE, and JVM

To understand the architecture clearly:

 JVM → Executes Java bytecode

 JRE = JVM + Libraries (run me environment)

 JDK = JRE + Development tools (compiler, debugger, etc.)

So the hierarchy becomes:

JDK → JRE → JVM

Conclusion

The JVM is the core engine that executes Java bytecode and ensures pla orm independence,
while the JRE provides the complete run me environment required to run Java applica ons,
including the JVM and standard libraries. Together they form the founda on of Java’s portable
and secure execu on model.

Q5. Write a Java program to handle mul ple excep ons using try–catch–finally.

class Mul pleExcep on {

public sta c void main(String[] args) {


try {

int a = 10;

int b = 0;

int c = a / b; // Arithme cExcep on

int arr[] = {1, 2, 3};

[Link](arr[5]); // ArrayIndexOutOfBoundsExcep on

catch (Arithme cExcep on e) {

[Link]("Arithme c Excep on: Division by zero");

catch (ArrayIndexOutOfBoundsExcep on e) {

[Link]("Array Index Out Of Bounds Excep on");

catch (Excep on e) {

[Link]("General Excep on");

finally {

[Link]("Finally block always executes");

}
This program demonstrates mul ple excep on handling using mul ple catch blocks and a
finally block which always executes.

Q6. Write a Java program that creates two threads – one to print even numbers and the other
for odd numbers.

class EvenThread extends Thread {

public void run() {

for(int i = 2; i <= 10; i += 2) {

[Link]("Even: " + i);

class OddThread extends Thread {

public void run() {

for(int i = 1; i <= 10; i += 2) {

[Link]("Odd: " + i);

public class ThreadExample {

public sta c void main(String[] args) {

EvenThread t1 = new EvenThread();

OddThread t2 = new OddThread();

[Link]();
[Link]();

In this program, two threads run concurrently:

 One thread prints even numbers.

 The other thread prints odd numbers.

Q7. Explain abstrac on and abstract classes in Java. Describe abstract method with example.

Abstrac on is an Object-Oriented Programming concept that focuses on showing only essen al


features while hiding implementa on details. It helps reduce complexity and improves code
security.

In Java, abstrac on can be achieved using abstract classes and interfaces.

Abstract Class

An abstract class is a class that is declared using the abstract keyword.


It cannot be instan ated (objects cannot be created directly from it). It may contain abstract
methods as well as normal methods.

Abstract classes are mainly used when some methods must be implemented by subclasses.

Abstract Method

An abstract method is a method that does not have a body. It only contains the method
declara on and must be implemented in the subclass.

Syntax:

abstract void methodName();

Example Program

abstract class Animal {

abstract void sound(); // abstract method

void sleep() {

[Link]("Animal is sleeping");
}

class Dog extends Animal {

void sound() {

[Link]("Dog barks");

class TestAbstract {

public sta c void main(String[] args) {

Dog d = new Dog();

[Link]();

[Link]();

In this example:

 Animal is an abstract class.

 sound() is an abstract method.

 The Dog class provides the implementa on of the abstract method.

Q8. Describe the ways to create threads in Java with suitable code. Also explain which
method is more suitable.

Threads in Java allow mul ple tasks to run concurrently, improving program performance.

There are two main ways to create threads in Java.

1. By Extending the Thread Class


In this method, a class extends the Thread class and overrides the run() method.

Example:

class MyThread extends Thread {

public void run() {

[Link]("Thread is running");

public sta c void main(String[] args) {

MyThread t1 = new MyThread();

[Link]();

Here, the start() method creates a new thread and calls the run() method.

2. By Implemen ng the Runnable Interface

In this method, a class implements the Runnable interface and defines the run() method.

Example:

class MyThread implements Runnable {

public void run() {

[Link]("Thread is running");

public sta c void main(String[] args) {

MyThread obj = new MyThread();

Thread t1 = new Thread(obj);

[Link]();
}

Which Method is More Suitable?

The Runnable interface method is more suitable because:

 Java supports single inheritance, so extending Thread prevents the class from extending
another class.

 Using Runnable allows the class to extend another class while s ll crea ng threads.

 It promotes be er object-oriented design and flexibility.

Therefore, implemen ng the Runnable interface is generally preferred for crea ng threads in
Java.

Q9. Illustrate polymorphism and its types in Java. Differen ate between compile- me and
run- me polymorphism.

Polymorphism means “many forms.” In Java, polymorphism allows a method or object to


behave differently in different situa ons. It is an important feature of Object-Oriented
Programming (OOP) that increases flexibility and reusability of code.

Types of Polymorphism in Java

1. Compile-Time Polymorphism (Method Overloading)


This type of polymorphism occurs when mul ple methods have the same name but different
parameters in the same class. The method to be called is decided at compile me.

Example idea:

add(int a, int b)

add(int a, int b, int c)

2. Run-Time Polymorphism (Method Overriding)


This occurs when a subclass provides a specific implementa on of a method already defined
in the parent class. The method call is resolved during run me.

Difference between Compile-Time and Run-Time Polymorphism


Feature Compile-Time Polymorphism Run-Time Polymorphism

Also called Method Overloading Method Overriding

Time of decision Compile me Run me

Method parameters Must be different Same parameters

Inheritance required No Yes

Example: Method Overriding using Shape and Rectangle

class Shape {

void displayArea() {

[Link]("Area of shape");

class Rectangle extends Shape {

void displayArea() {

int length = 10;

int width = 5;

int area = length * width;

[Link]("Area of Rectangle = " + area);

public sta c void main(String[] args) {

Rectangle r = new Rectangle();

[Link]();

}
}

In this example, the Rectangle class overrides the displayArea() method of the Shape class,
demonstra ng run- me polymorphism.

Q10. Illustrate Constructors and their applica ons in Java.

A constructor in Java is a special method used to ini alize objects when they are created. It has
the same name as the class and does not have a return type.

Constructors are automa cally called when an object is created using the new keyword.

Applica ons of Constructors

 Ini alize object variables

 Assign ini al values to a ributes

 Simplify object crea on

 Ensure objects start with valid data

Types of Constructors in Java

1. Default Constructor
A constructor with no parameters. It assigns default values to variables.

2. Parameterized Constructor
A constructor that accepts parameters to ini alize variables with specific values.

3. Copy Constructor (Conceptual in Java)


Used to copy values from one object to another.

Example: Student Class with All-Argument Constructor

class Student {

int roll_number;

String name;

String branch;
String email;

Student(int roll_number, String name, String branch, String email) {

this.roll_number = roll_number;

[Link] = name;

[Link] = branch;

[Link] = email;

void display() {

[Link](roll_number + " " + name + " " + branch + " " + email);

public sta c void main(String[] args) {

Student s1 = new Student(1, "Aryan", "CSE", "aryan@[Link]");

Student s2 = new Student(2, "Rahul", "CSE", "rahul@[Link]");

[Link]();

[Link]();

In this program:

 Student class has an all-argument constructor.

 Two objects (s1 and s2) are created using this constructor.

 Each object is ini alized with different values.


Q11Differen ate between checked and unchecked excep ons in Java.

Excep ons are events that occur during program execu on and disrupt the normal flow of a
program. In Java, excep ons are mainly classified into checked excep ons and unchecked
excep ons.

Feature Checked Excep ons Unchecked Excep ons

Checking
Checked at compile me Occur at run me
me

Must be handled using try-catch or


Handling Handling is op onal
throws

Cause Usually due to external condi ons Usually due to programming errors

Arithme cExcep on,


Examples IOExcep on, SQLExcep on
NullPointerExcep on

Checked excep ons are verified by the compiler before execu on, while unchecked excep ons
occur during program execu on due to logical errors.

Java Program to Demonstrate Arithme c Excep on Handling;

class Arithme cExcep onDemo {

public sta c void main(String[] args) {

try {

int a = 10;

int b = 0;

int c = a / b;

[Link]("Result = " + c);

catch (Arithme cExcep on e) {

[Link]("Arithme c Excep on: Division by zero is not allowed");

finally {
[Link]("Program execu on completed");

Q12. Differen ate between with suitable examples: 1. Character streams and Byte Streams 2.
wait() and no fy():

Answer khud search kar lena

You might also like