0% found this document useful (0 votes)
8 views137 pages

Java Interview Questions and Answer1

The document provides a comprehensive overview of core Java concepts, including differences between JDK and JRE, platform independence, abstract classes vs interfaces, final vs finally vs finalize, method overloading vs overriding, access modifiers, constructor overloading, and the use of the super keyword. Each concept is explained with definitions, examples, and real-life analogies to enhance understanding. The content is structured as a Q&A format, making it suitable for Java interview preparation.

Uploaded by

Brilliant 4444
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)
8 views137 pages

Java Interview Questions and Answer1

The document provides a comprehensive overview of core Java concepts, including differences between JDK and JRE, platform independence, abstract classes vs interfaces, final vs finally vs finalize, method overloading vs overriding, access modifiers, constructor overloading, and the use of the super keyword. Each concept is explained with definitions, examples, and real-life analogies to enhance understanding. The content is structured as a Q&A format, making it suitable for Java interview preparation.

Uploaded by

Brilliant 4444
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

Java Interview Questions And Answer

( CORE JAVA CONCEPT )

Q.1 What is difference between JDK and JRE ?


Ans: ➤ JDK kya hai?
JDK ek development kit hai jo Java applications ko banane (develop) karne ke liye use hota
hai.

Isme kya kya hota hai?

• JRE (Java Runtime Environment) included hoti hai


• Compiler (javac) → Java code ko .java se .class banata hai
• Debugger
• Java tools (like javadoc, jar, etc.)

Use:
JDK ka use Java ka software, apps ya website banane ke liye hota hai.

JRE (Java Runtime Environment)

➤ JRE kya hai?


JRE sirf ek runtime environment hai — iska use Java program ko chalane (run) ke liye hota
hai.

Isme kya hota hai?


• JVM (Java Virtual Machine) → Java code ko run karta hai
• Core libraries ([Link])
• Java class loader

Isme compiler nahi hota — matlab Java code likh nahi sakte, sirf run kar sakte ho.

Real-Life Example se Samjho:

JDK = Chef + Kitchen + Ingredients


• Agar aap khana banana chahte ho (Java program develop karna), to aapko:
o Chef (Compiler) chahiye
o Ingredients (Libraries, Tools) chahiye
o Kitchen (Runtime environment) chahiye
=> Yeh sab mil ke JDK banta hai

JRE = Sirf Kitchen + Stove


• Agar aapko sirf banaya hua khana khana hai (Java program run karna hai), to:
o Sirf kitchen aur stove chahiye (JRE)
o Aap khana khud nahi bana sakte (no compiler)

Q.2 Why is Java platform independent language ?


Ans: Platform Independent ka matlab kya hota hai?
Platform independent ka matlab hota hai ki ek baar likha gaya program, kisi bhi operating
system (Windows, Mac, Linux) par bina code ko dobara likhe ya badle chalaya jaa sakta hai.

Java Platform Independent kaise hai?


Java is platform independent because of its special architecture:
Step-by-step process:

1. Java Code likho (e.g., .java file)

2. Java Compiler (javac) us code ko Bytecode me convert karta hai (.class file)

3. Bytecode ko Java Virtual Machine (JVM) ke through kisi bhi operating system par
run kiya ja sakta hai.

JVM har operating system ke liye alag hoti hai, lekin bytecode sabme common rehta hai.

Real-Life Example:
Example Situation:
Maan lo aapne ek Java program banaya jo student ka data manage karta hai —
[Link].
1. Aapne Windows pe code likha aur compile karke .class file banayi.
2. Ab usi .class file ko aap Mac ya Linux wale dost ko bhejte ho.
3. Wo sirf apne system me JVM install karke us program ko chala sakta hai — bina code
change kiye.

Isiliye kehte hain: "Write Once, Run Anywhere (WORA)" – Java ka famous slogan.

Q.3 What is difference between abstract class and an interface?


ANS: 1. Abstract Class (आंशिक class) kya hoti hai?

• Ek abstract class wo hoti hai jisme kuch methods define kiye jaate hain, aur kuch sirf
declare (abstract) hote hain.
• Ye ek base class ban jaati hai jise extend/inherit kiya jaata hai.
• Abstract class mein constructor, non-abstract methods, fields/variables ho sakte
hain.

Real-life Example (Abstract Class):


Vehicle ek abstract class hai:
java
CopyEdit
abstract class Vehicle {
void startEngine() {
[Link]("Engine started");
}

abstract void fuelType(); // define nahi kiya, sirf bataya


}
Fir hum ise inherit karte hain:
java
CopyEdit
class Car extends Vehicle {
void fuelType() {
[Link]("Petrol or Diesel");
}
}
Yaha startEngine() to sabhi vehicles mein common hai, isliye defined hai.
Par fuelType() alag ho sakti hai, isliye subclass define karega.

2. Interface kya hota hai?


• Interface ek 100% abstract blueprint hota hai.
• Isme sirf method signatures hote hain (Java 8 ke baad default method allowed hai).
• Aap multiple interfaces implement kar sakte ho (Java supports multiple inheritance
with interfaces).
• Interface mein constructor nahi hota.

Real-life Example (Interface):


Flyable ek interface hai:
java
CopyEdit
interface Flyable {
void fly(); // method ka sirf naam diya gaya
}
Ab koi bhi class jo fly kar sakti hai, wo isse implement karegi:
java
CopyEdit
class Airplane implements Flyable {
public void fly() {
[Link]("Flying in the sky");
}
}

class Bird implements Flyable {


public void fly() {
[Link]("Bird flies using wings");
}
}

Yaha Flyable ek ability hai, jo kisi bhi class ko di ja sakti hai — chahe bird ho ya plane.

Main Differences Between Abstract Class vs Interface:

Feature Abstract Class Interface

Keyword abstract class interface

Only one class can be extended (single Multiple interfaces can be


Inheritance
inheritance) implemented

Can have both abstract & concrete All methods are abstract (by
Methods
methods default)

Constructor Can have constructor Cannot have constructor

Variables Can have instance variables Only static final constants allowed

Used for "is-a" relationship (e.g., Car is a Used to define "capabilities" (e.g.,
Purpose
Vehicle) can Fly)

Conclusion:

• Use Abstract Class jab aapko common logic reuse karna ho.

• Use Interface jab aapko common capability provide karni ho (like Flyable,
Drivable, Serializable).

Q.4 Why is difference between final , finally and finalize?


Ans: 1. final (Keyword)

Purpose:
final ek modifier hai jo:
• Variable ko constant banata hai
• Method ko override hone se rokta hai
• Class ko inherit hone se rokta hai
Real Life Example:
Socho tumhare college me roll number ek baar assign ho gaya to wo kabhi change nahi
hota. Same way, agar kisi variable ko final declare kar diya, to uski value kabhi change nahi
ho sakti.

Syntax Examples:
final int x = 10;

x = 20; // Error: Cannot assign a value to final variable


final class Vehicle {
// no one can extend this class
}
final void show() {
// this method can't be overridden
}

2. finally (Block)

Purpose:
finally block exception handling me use hota hai. Ye block har haal me chalta hai, chahe
exception aaye ya na aaye.

Real Life Example:


Socho tumne gas burner chalu kiya aur khaana banane lage. Chahe khaana jale ya sahi
bane, finally tum gas band zaroor karte ho — waise hi, finally block hamesha execute hota
hai.

Syntax Example:
try {

int a = 10 / 0; // Exception
} catch (Exception e) {
[Link]("Exception occurred");
} finally {

[Link]("Cleanup done"); // Always runs


}

3. finalize() (Method)

Purpose:
finalize() ek method hai jo Object destroy hone se pehle (garbage collect hone se pehle) call
hota hai. Iska use cleanup ke liye hota hai (like memory release, closing connection etc.)
Note: Java 9 ke baad finalize() ko deprecated kar diya gaya hai kyunki ye unpredictable
behavior de sakta hai.

Real Life Example:


Socho ek hotel guest check-out karta hai to staff finalize() jaisa kaam karta hai: room clean
karta hai, light band karta hai — means before object removal, kuch final cleanup.

Syntax Example:
protected void finalize() throws Throwable {
[Link]("Object is being garbage collected");
}
public static void main(String[] args) {
FinalizeExample obj = new FinalizeExample();
obj = null;
[Link](); // Request for garbage collection
}

Q.5 What is difference between method overloading and method


overriding ?
Ans: Method Overloading (Same method name, different parameters)

Kya hota hai?


Jab ek hi class ke andar same method name ke multiple versions hote hain, lekin unke
parameters alag hote hain, usse Method Overloading kehte hain.

Syntax:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}

Real-Life Example:
Socho tumhare paas ek Calculator app hai:
• Jab user do number deta hai: add(2, 3) → 5
• Jab user teen number deta hai: add(2, 3, 4) → 9
• Jab user decimal deta hai: add(2.5, 3.5) → 6.0
Ek hi "add" method, lekin alag input ke hisaab se alag behavior. That's method
overloading.

Method Overriding (Same method name in child class)

Kya hota hai?


Jab parent class me koi method defined hoti hai aur child class us method ko dubara likhti
hai apne hisaab se, usse Method Overriding kehte hain.

Syntax:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}}

Real-Life Example:
Socho tumhare paas ek Animal class hai. Har animal ka sound() method hai, lekin:
• Dog ke liye: Dog barks
• Cat ke liye: Cat meows
Toh jab tum [Link]() call karte ho, actual output object ke type pe depend karta hai
— this is method overriding.

Difference Chart

Feature Method Overloading Method Overriding

Class Same class Parent-child (inheritance) required

Parameters Must be different Must be same

Return Type Can be same or different Should be same or covariant

Polymorphism Compile-time (static) Runtime (dynamic)

Annotation (@Override) Not used Required for clarity in Java

Q.6 What is difference between a private and a protected modifier ?


Ans: 1. Private Modifier
Private ka matlab hota hai "Sirf apne class ke andar hi access".
Koi aur class ya subclass is variable ya method ko directly access nahi kar sakta.

Use:
• Jab aap kisi cheez ko completely hide karna chahte ho from outside world.
Syntax
class BankAccount {
private double balance;
public BankAccount() {
balance = 0;
}
private void calculateInterest() {
// interest logic
}
}

Real-Life Example:
Bank Account ki balance sheet
• balance variable ko private banaya gaya hai.
• Sirf BankAccount class hi usko access kar sakti hai.
• Bahar ka koi customer ya subclass directly balance ko access nahi kar sakta.

Secure, encapsulated. Not inherited directly.

2. Protected Modifier
Protected ka matlab hota hai "Sirf apni class aur uske child (inherited) class me access".
Yeh private se thoda zyada flexible hota hai.

Use:
• Jab aap chahte ho ki subclass kuch internals ko use ya override kar sake.

Syntax:
class Person {
protected String name;
}
class Student extends Person {
public void displayName() {
[Link]("Name: " + name); // allowed
}
}

Real-Life Example:
Father's property inherited by child
• Suppose Father class me protected car hai.
• Son class (jo inherit karta hai) us car ko access kar sakta hai.
• Lekin Society class (jo inherit nahi karti) access nahi kar sakti.

Inheritable. Useful for subclasses. Not accessible outside hierarchy.

Summary Table:

Modifier Access in Same Class Access in Subclass Access Outside Class

private Yes No No

protected Yes Yes No

Q.7 What is Constructor overloading in Java ?


Ans: Definition:
Constructor Overloading Java mein ek concept hai jisme ek hi class ke andar multiple
constructors banaye jaate hain different parameters ke sath.
Matlab: Constructor ka naam same hoga (jo class ka naam hota hai), lekin parameters ka
type, number ya order alag-alag hoga.

Kyu use karte hain Constructor Overloading?


• Jab hum ek object ko different-different tarike se initialize karna chahte hain.
• Default value deni ho kabhi, kabhi full detail se object banana ho — dono ka support
chahiye hota hai.

Syntax (Basic Example):


class Student {
String name;
int age;

// Default constructor
Student() {
name = "Unknown";
age = 0;
}

// Constructor with one parameter


Student(String n) {
name = n;
age = 0;
}

// Constructor with two parameters


Student(String n, int a) {
name = n;
age = a;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // Default
Student s2 = new Student("Shrikant"); // Only name
Student s3 = new Student("Mansi", 21); // Name and age
[Link]();
[Link]();
[Link]();
}
}

Real Life Example (Hinglish):


Socho aap ek "Pizza" order kar rahe ho:
class Pizza {
String size;
String topping;
// Default pizza
Pizza() {
size = "Medium";
topping = "Cheese";
}
// Pizza with size only
Pizza(String s) {
size = s;
topping = "Cheese";
}
// Pizza with size and topping
Pizza(String s, String t) {
size = s;
topping = t;
}
void showOrder() {
[Link]("Pizza size: " + size + ", Topping: " + topping);
}
}
public class PizzaOrder {
public static void main(String[] args) {
Pizza p1 = new Pizza(); // Default order
Pizza p2 = new Pizza("Large"); // Custom size
Pizza p3 = new Pizza("Small", "Paneer"); // Custom size + topping
[Link]();
[Link]();
[Link]();
}
}

Output:
Pizza size: Medium, Topping: Cheese
Pizza size: Large, Topping: Cheese
Pizza size: Small, Topping: Paneer

Key Points:
• Constructor Overloading compile time pe decide hoti hai (Compile-Time
Polymorphism).
• Overloaded constructors alag-alag arguments accept karte hain.
• Return type nahi hota constructor ka.
• Isse flexibility milti hai object creation mein.

Q.8 What is the use of super keyword in Java ?


Ans: Definition:

Java में super एक keyword hai jo subclass (child class) ke andar parent class (superclass) ke
constructor, methods, ya variables ko access karne ke liye use hota hai.

super ka 3 major use hota hai:


Use Case Explanation

1. super() Parent class ka constructor call karne ke liye

2. [Link]() Parent class ka method call karne ke liye

3. [Link] Parent class ka variable access karne ke liye

1. super() – Constructor Call

Jab child class banaate ho, aur parent class ka constructor bhi run karwana chahte ho:
class Animal {
Animal() {
[Link]("Animal constructor called");
}
}
class Dog extends Animal {
Dog() {
super(); // Parent class ka constructor call
[Link]("Dog constructor called");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
}
}

Output:
Animal constructor called
Dog constructor called
2. [Link]() – Parent Method Call

Jab parent aur child dono mein same naam ka method ho (Method Overriding), aur
tum parent wala method bhi use karna chaho:
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
[Link](); // Parent class ka method
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}

Output:
Animal makes sound
Dog barks

3. [Link] – Parent Variable Access

Jab child aur parent dono mein same naam ka variable ho, aur tum parent wala access
karna chaho:
class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void printName() {
[Link](name); // Dog
[Link]([Link]); // Animal
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}

Output:
Dog
Animal

Real Life Example (Hinglish Explanation)


Situation:
• Ek Vehicle class hai jo sabhi vehicles ke basic features rakhti hai.
• Fir ek Car class hai jo Vehicle se inherit karti hai.

class Vehicle {
int speed = 60;
void showSpeed() {
[Link]("Vehicle speed: " + speed + " km/h");
}
}
class Car extends Vehicle {
int speed = 120;
void showSpeed() {
[Link]("Car speed: " + speed + " km/h");
[Link]("Original Vehicle speed: " + [Link] + " km/h");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
[Link]();
}
}

Output:
Car speed: 120 km/h
Original Vehicle speed: 60 km/h

Real Life Connection:


• Jaise tumhare papa (Vehicle) bike chalaate the 60 km/h ki speed se.
• Tum (Car) naye ho aur 120 km/h se gaadi chalaate ho.
• Tum [Link] se papa ki old speed yaad kar rahe ho.

Q.9 What is the difference between static methods, static variables,


and static classes in Java?
Ans: Java me static keyword ka use class-level members ke liye hota hai, matlab jo
object se nahi balki class se jude hote hain.

1. Static Variable (Class Variable)

Definition:
Ek static variable class ka hota hai, na ki object ka. Iska matlab ye hai ki sabhi objects is
variable ko share karte hain.
Real-Life Example:
Socho ek college hai (class), aur us college ka common college name hai "XYZ College". Har
student ka naam alag hai, lekin college name sabhi ke liye same hai.

Java Code:
class Student {
int rollNo;
String name;
static String college = "XYZ College"; // static variable

Student(int roll, String n) {


rollNo = roll;
name = n;
}
void display() {
[Link](rollNo + " " + name + " " + college);
}
}

Output:
101 Rahul XYZ College
102 Priya XYZ College

2. Static Method

Definition:
static method ko bina object banaye call kiya ja sakta hai. Ye mostly utility ya helper ka
kaam karta hai.

Real-Life Example:
Socho ek calculator hai jisme tum add, subtract jaise methods bana rahe ho. Ye methods kisi
specific object par dependent nahi hote, ye sab ke liye common logic hota hai.
Java Code:
class Calculator {
static int add(int a, int b) { // static method
return a + b;
}
}

Usage:
int result = [Link](5, 3); // No need to create object
[Link](result);

Output:
8

3. Static Class (Nested Static Class)

Definition:
Java me sirf nested class static ho sakti hai, matlab ek class ke andar ek aur class. Static
nested class ka outer class ke object se koi relation nahi hota.

Real-Life Example:
Socho ek University class hai, aur uske andar ek Department class. Department class ko
static bana diya gaya hai, matlab wo independently exist kar sakti hai bina University ka
object banaye.

Java Code:
class University {
static class Department {
void show() {
[Link]("Department of Computer Science");
}
}
}
Usage:
[Link] dept = new [Link]();
[Link]();

Output:
Department of Computer Science

Comparison Table:

Feature Static Variable Static Method Static Class

Belongs to Class Class Outer Class

[Link]
Access via [Link] [Link]()
obj = ...

Requires No (for static nested


No No
Object? class)

Shared data (e.g., Utility methods (e.g., Logical grouping of


Use Case
college name) Calculator logic) classes

Summary in Hinglish:
• Static Variable → Common property sabhi objects ke liye (e.g., college name).
• Static Method → Bina object banaye call karne wali method (e.g., add()).
• Static Class → Nested class jo independently use ho sakti hai (e.g., Department inside
University).

Q.10 What exactly is [Link] in Java?


Ans: [Link] Java ka ek built-in method hai jo output ko console (screen) par
print karne ke liye use hota hai.

Breakdown of [Link]
1. System:
Java ka ek predefined class hai jo standard input, output, and error streams ko handle karta
hai.
2. out:
Ye System class ka static object hai jo standard output stream ko represent karta hai —
yaani ki screen ya console.
3. println:
Ye ek method hai jo out object se call hota hai.
println ka matlab hota hai — print line
Yeh jo bhi message tum pass karte ho, use print karta hai aur ek new line mein chala jata
hai.

Real-Life Example (Hindi Mein Samajho):


Socho tum ek announcement mic use kar rahe ho.

• Tumhara System = Mic system (पूरी मशीन)

• out = Speaker (जिधर आवाज़ िाती है )

• println() = वो action जिससे आवाज़ broadcast होती है

[Link]("Namaste, sabhi students!");


Iska matlab:

Mic system ke speaker se bolo: “नमस्ते, सभी स्टूडेंट्स!”

Console par output dikhega:


Namaste, sabhi students!

Q.11 What part of memory - Stack or Heap - is cleaned in the garbage


collection process?
Ans: JavaScript, Java, Python jaise high-level languages me Garbage Collection (GC) ek
automatic memory management process hota hai.

Garbage Collection kis memory part me hota hai?

Heap memory me hota hai.


Stack vs Heap – Pehle samjho kya difference hai:
1. Stack Memory –

Yah short-term memory hai.


Isme function ke local variables aur execution context store hote hain.
Yeh automatically clean ho jaata hai jaise hi function execution khatam ho jaata hai.
Stack memory fixed size hoti hai.

Example:
function greet() {
let name = "Shrikant"; // Yeh stack me store hoga
}

2. Heap Memory –

Yah long-term memory hai.


Isme objects, arrays, functions jaise complex aur dynamic data store hota hai.
Heap memory ko manually manage nahi karte – Garbage Collector karta hai.

Example:
let person = {
name: "Shrikant",
age: 21
};
// 'person' object heap me store hoga

Garbage Collection kaam kaise karta hai?


Jab koi object ya variable heap me store hone ke baad kabhi use nahi ho raha, to GC usse
detect karta hai aur usse delete (clean) kar deta hai.

Rule:
"If there is no reference to an object left in the program, it is considered garbage."

Real Life Example (Hinglish):


Socho ki tum ek hostel room (heap) me reh rahe ho.
Har student (object) apne room me tab tak rahta hai jab tak uska naam register (reference)
me hai.
Ek din, agar kisi student ka naam register se hata diya gaya –
to hostel warden (Garbage Collector) uska room clean kar deta hai, taaki naye student ko
diya ja sake.

JS Example:
let student = {
name: "Rahul"
};
// Now this student is in heap and referenced by 'student'
student = null; // Reference hata diya
// Garbage Collector detect karega ki "Rahul" object ab kisi bhi variable se linked nahi hai,
// to usse memory se hata diya jaayega (heap clean)

Summary (in points):

Feature Stack Heap

Store karta hai Primitive values, function calls Objects, Arrays, Functions

Memory management Automatically during function call Garbage Collector karta hai

Garbage collection hoti hai? No Yes (heap only)

Speed Fast Comparatively Slower

(Object-Oriented Programming:)
Q.1 What are the Object Oriented Features supported by Java?
Ans: Java ek Object-Oriented Programming Language (OOP) hai, jiska matlab hai ki Java
mein sab kuch objects ke form mein socha jaata hai. Object-Oriented Programming ka main
goal hai ki code modular, reusable, flexible aur real-world problems se easily map ho sake.
Java ke Object-Oriented Features
1. Class & Object

Kya hai?
• Class ek blueprint hai jisme hum object ke structure aur behavior define karte hain.
• Object real entity hai jo class ke base par banta hai.

Real Life Example:


• Class: Car
→ Properties: color, model, speed
→ Behaviors: start(), stop()
• Object: myCar = new Car();
→ myCar is a real car with color red, model Swift.

Java Example:
class Car {
String color;
void start() {
[Link]("Car Started");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car(); // object creation
[Link] = "Red";
[Link](); // Car Started
}
}

2. Encapsulation

Kya hai?
• Jab data (variables) aur methods ko ek hi unit (class) mein bundle kar diya jaata hai.
• Data ko private banakar usko access karne ke liye getters/setters use kiye jaate hain.

Real Life Example:


• Tumhara ATM card: Uska PIN (data) private hota hai aur access sirf authorized
methods se hota hai.

Java Example:
class Student {
private int age; // Encapsulated data
public void setAge(int a) {
age = a;
}
public int getAge() {
return age;
}
}

3. Inheritance

Kya hai?
• Jab ek class doosri class ke properties aur methods ko inherit (adhikar) karti hai.
• Code reuse ke liye useful hai.

Real Life Example:


• Father class → Property: house
• Son class → Father ke house ko inherit karta hai

Java Example:
class Animal {
void eat() {
[Link]("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
}
}

4. Polymorphism

Kya hai?
• Poly = many, morph = forms
• Ek function ya object ka multiple forms mein behave karna.
Types:
• Compile-time (Method Overloading)
• Run-time (Method Overriding)

Real Life Example:


• Ek person:
o Ghar pe beta, office mein employee, ground pe player → same person,
different roles

Java Examples:
Method Overloading (Compile-Time):
class Math {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Method Overriding (Run-Time):
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}

5. Abstraction

Kya hai?
• Sirf essential features ko dikhana, aur unnecessary details ko hide karna.
• Achieve hota hai through abstract class ya interface.

Real Life Example:


• Car ka steering wheel use karte ho, lekin andar engine kaise kaam karta hai, uski
detail nahi dekhte.

Java Example:
abstract class Shape {
abstract void draw(); // only declaration
}
class Circle extends Shape {
void draw() {
[Link]("Drawing Circle");
}
}
6. Constructor

Kya hai?
• Special method hota hai jo object banate waqt call hota hai.
• Ye object ko initial state deta hai.

Real Life Example:


• Jab tum nayi car kharidte ho, wo default settings ke saath aati hai.

Java Example:
class Student {
String name;

Student(String n) {
name = n;
}
}

7. Message Passing

Kya hai?
• Objects aapas mein message pass karke kaam karte hain (method calling ke through).

Real Life Example:


• Tum mobile se kisi friend ko message bhejte ho → wo us par action leta hai.

Java Example:
class A {
void show() {
[Link]("Message received!");
}
}

class Main {
public static void main(String[] args) {
A obj = new A();
[Link](); // Message passing
}
}

Conclusion (Summary Table)

Feature Description Real Life Example

Class & Object Blueprint and Instance Car class, myCar object

Encapsulation Data hiding using private + getter/setter ATM pin

Inheritance One class inherits another Father to Son

Polymorphism One name, many forms Person in multiple roles

Abstraction Show important, hide details Driving car without engine details

Constructor Initializes object New car setup

Message Passing Objects calling methods of others Mobile message

Q.2 What are the different access specifiers used in Java?


Ans: Java में Access Specifiers (या Access Modifiers) का उपयोग यह तय करने के लिए
ककया िाता है कक ककसी class, method, variable या constructor को कहााँ-कहााँ से access
ककया िा सकता है ।
ये 4 प्रकार के होते हैं:

1. private

Meaning:

private members केवि उसी class के अंदर से access ककए िा सकते हैं। ककसी दस
ू री class से
नहीं।

Real-Life Example:
मान िो एक ATM machine का PIN number, वो लसर्फ user (i.e. class itself) को पता होता है ।
कोई और उसे access नहीं कर सकता।

Java Example:
class BankAccount {
private int pin = 1234;
private void showPin() {
[Link]("PIN is: " + pin);
}
}

Access:
java
CopyEdit
BankAccount acc = new BankAccount();

[Link]([Link]); // Error

[Link](); // Error

2. public

Meaning:

public members को कहीं से भी access ककया िा सकता है — ककसी भी package या class से।

Real-Life Example:

मान िो एक hospital का emergency number — कोई भी कभी भी call कर सकता है ।

Java Example:
public class Student {
public String name = "Shrikant";
public void showName() {
[Link]("Student name: " + name);
}
}
Access:
java
CopyEdit
Student s = new Student();

[Link]([Link]); // OK

[Link](); // OK

3. protected

Meaning:
protected members:

• उसी class में ,

• उसी package में ,

• और subclass (child class) में access ककए िा सकते हैं (चाहे अिग package में हो)।

Real-Life Example:

मान िो कोई family का ववरासत वािा property — family members और उनके बच्चे use कर
सकते हैं, िेककन कोई outsider नहीं।

Java Example:
class Animal {
protected void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {

sound(); // Accessible because it's inherited


}
}
4. Default (No Modifier)

Meaning:

अगर तुम कोई access specifier नहीं िगाते तो वो default होता है ।


ऐसे members लसर्फ उसी package के अंदर access ककए िा सकते हैं।

Real-Life Example:

School की internal circular, िो लसर्फ उस school के students और teachers को ददखती है —


outsiders को नहीं।

Java Example:
class Employee {
String dept = "HR"; // default access
void showDept() {
[Link]("Department: " + dept);
}
}

Access in another package:

अगर कोई दस
ू री class दस
ू री package में है , तो default members access नहीं कर पाएगी।

Summary Table

Access
कहााँ से Access कर सकते हैं Real-Life Example
Specifier

private केवि उसी class से ATM PIN, Aadhaar number

default उसी package से स्कूि की internal notice

उसी package + subclass (चाहे दस


ू रे
protected Family का property
package में )

Emergency number, Website


public कहीं से भी (दस
ू रे package/class से भी)
homepage
Q.3 What is the difference between composition and inheritance?
Ans: Composition और Inheritance — दोनों Object-Oriented Programming (OOP) की core
concepts हैं, िेककन इनका use-case, design approach और flexibility अिग-अिग होती है ।

1. Inheritance (विरासत / "is-a" relationship)

Concept:

Inheritance में एक child class (subclass) एक parent class (superclass) से सारे properties और
behaviors (methods) "विरासत में " inherit कर िेती है।

"is-a" relationship
Example: A Dog is a Animal

Real-Life Example:

मान िो एक class है Animal, और उससे Dog और Cat inherit कर रहे हैं।

class Animal {
void eat() {
[Link]("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog is barking");
}
}
java
CopyEdit
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited method
[Link](); // own method
}
}

Advantages:

• Code reuse होता है।

• Logical hierarchy बनती है ।

Disadvantages:

• Tight coupling हो िाता है ।

• एक बार inherit कर लिया, तो subclass सारे unnecessary methods भी inherit कर िेता


है (चाहे ज़रूरत न हो)।

2. Composition ("has-a" relationship)

Concept:

Composition में एक class दस


ू री class को अपने अंदर object की तरह रखती है और उसके
functionalities का use करती है।

"has-a" relationship
Example: A Car has an Engine

Real-Life Example:

मान िो एक Engine class है और उसे Car class में use ककया गया है , inherit नह ।ं

class Engine {
void start() {
[Link]("Engine started");
}
}
class Car {
Engine engine = new Engine(); // Composition
void drive() {
[Link]();
[Link]("Car is driving");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
[Link]();
}
}

Advantages:

• Loose coupling रहता है ।

• Flexibility ज्यादा होती है ।

• Reusability बढ़ती है — एक ही class कई िगह reuse हो सकती है ।

Disadvantages:

• थोडा ज़्यादा code लिखना पडता है (boilerplate).

Difference Table (हहंद में तुलना):

Feature Inheritance (विरासत) Composition (संयोजन)

Relationship Type "is-a" (िैसे Dog is an Animal) "has-a" (िैसे Car has an Engine)

Tight Coupling (ज़्यादा


Coupling Loose Coupling (कम dependency)
dependency)

Reusability Class hierarchy बनती है ज़्यादा flexible reuse possible

Flexibility कम flexible ज़्यादा flexible

Runtime Yes (object को replace कर


No
Changeable? सकते हैं)
Feature Inheritance (विरासत) Composition (संयोजन)

Example Dog extends Animal Car has Engine

Q.4 What is the purpose of an abstract class?


Ans: Java में abstract class का purpose होता है — एक ऐसा base class structure provide
करना, जिसे हम directly object बना के use नह ं कर सकते, िेककन inherited करके use कर
सकते हैं।

यह class कुछ functionalities को define कर सकती है , और कुछ को abstract छोड़ दे ती है


(i.e., unimplemented), जिसे उसके child class को implement करना पडता है।

1. Definition
abstract class ek aesi class hoti hai jo fully complete nahi hoti — isme kuch methods hote
hain jo sirf declare hote hain, lekin implement nahi hote. In methods ko abstract methods
kehte hain.
Iska use tab hota hai jab hum ek base class banana chahte hain jisme basic design ho aur
future mein subclasses usse extend karke apna behavior define karein.

Real-Life Example:

मान िो ek Vehicle base class hai. अब हम नहीं िानते कक हर vehicle kaise चिाया िाता है
— Bus, Bike, Car सब अिग-अिग तरीके से चिते हैं।
तो हम Vehicle को abstract बना दें गे और उसका एक abstract method बना दें गे start()।

Analogy:
• Vehicle = abstract class
• start() = abstract method

• Car, Bike = subclasses िो इसे implement करें गे

Java Code Example:

Abstract Class:
abstract class Vehicle {
abstract void start(); // abstract method
void fuel() {
[Link]("Fuels can be petrol, diesel or electric.");
}
}

Subclass:
class Car extends Vehicle {
void start() {
[Link]("Car starts with a key or button.");
}
}
class Bike extends Vehicle {
void start() {
[Link]("Bike starts with a kick or self-start.");
}
}

Main Class:
public class Main {
public static void main(String[] args) {
Vehicle v1 = new Car();
[Link](); // Output: Car starts with a key or button.
[Link](); // Output: Fuels can be petrol, diesel or electric.

Vehicle v2 = new Bike();


[Link](); // Output: Bike starts with a kick or self-start.
}
}
Key Points (Hinglish):

Feature Explanation

abstract class Base class hoti hai jisko direct use nahi kar sakte

abstract method Method jiska sirf naam hota hai, body nahi

extends keyword Subclass banaane ke liye use hota hai

object Abstract class ka object direct nahi bana sakte

partial implementation Abstract class kuch methods implement kar sakti hai

Can you do this?

Vehicle v = new Vehicle(); // Error - Cannot instantiate abstract class

Real-Life Abstract Class Examples (Software mein):

Abstract Class Subclass

Animal Dog, Cat, Tiger

Shape Circle, Rectangle

Employee Manager, Developer

Vehicle Car, Bike, Truck

Final Thought:

िब भी आपको एक ऐसा template ya blueprint चादहए जिसमें कुछ common functionality


defined हो और कुछ subclasses को define करनी हो — वहां abstract class perfect solution
है .

Q.5 What are the differences between constructor and method of a


class in Java?
Ans: Java में constructor और method दोनों ही ककसी class के important parts होते हैं,
िेककन इनका काम और behavior अिग होता है।

नीचे detailed comparison + real-life example के साथ समझाया गया है


Constructor vs Method —

Feature Constructor Method

Purpose Object को initialize (िुरुआती state दे ने) ककसी object के behavior या


(उद्दे श्य) के लिए होता है functionality को define करता है

Name Class के same name का होता है कोई भी valid name हो सकता है

Return Type नह ं होता (ना void, ना कोई type) होता है (void, int, String, etc.)

Call कैसे होता Object बना कर method को call


Automatically िब object बनाते हैं (new)
है ? करना पडता है

हााँ, method भी overload ककए िा


Overloading हााँ, multiple constructors हो सकते हैं
सकते हैं

Constructor inherit नह ं होता, but super()


Inheritance में Methods inherit हो सकते हैं
से call हो सकता है

Java एक default constructor provide Method default नहीं होता,


Default form
करता है अगर तम
ु ने कोई न बनाया हो manually बनाना पडता है

Real-Life Example

मान लो तुम्हार class है Car

public class Car {


String model;
int speed;

// Constructor: िब object create करो, model set हो िाए

Car(String carModel) {
model = carModel;
speed = 0;
[Link](model + " car is ready!");
}

// Method: कुछ काम perform करता है , िैसे accelerate

void accelerate(int increase) {


speed += increase;
[Link](model + " is now at speed " + speed + " km/h");
}
}

Usage:
public class Main {
public static void main(String[] args) {

// Constructor call (auto call होता है new से)

Car myCar = new Car("Toyota");

// Method call
[Link](30);
}
}

Output:
Toyota car is ready!
Toyota is now at speed 30 km/h

याद रखने का Trick (Real-life Analogy):

Term Real-Life Example

िब आप नया phone खरीदते हो और initial setup करते हो (language, Wi-Fi,


Constructor
etc.) — ये constructor का काम है
Term Real-Life Example

Phone की daily functionalities — िैसे call करना, message भेिना — ये


Method
method का काम है

Quick Recap :

• Constructor = Object बनाने पर automatically चिता है , कोई return type नहीं।

• Method = Object बनने के बाद manually चिाते हैं, कुछ return कर सकता है ।

Q.6 What is the diamond problem in Java and how is it solved?


Ans: What is the Diamond Problem in Java?
Diamond Problem ek Multiple Inheritance se related concept hai. Ye tab hota hai jab ek
class do parent classes se inherit karti hai, aur dono parent ek hi base class se inherit karte
hain. Isse ambiguity (confusion) create hoti hai ki base class ka kaunsa version inherit hoga.

Problem Ka Shape — "Diamond"


Let's visualize:
A
/\
B C
\/
D
• Class B and C inherit from class A
• Class D inherits from both B and C
Ab agar A ke paas ek method display() hai, to jab D usse call karega to confusion hoga:
display() kis path se aaye — B se ya C se?

Java Mein Diamond Problem Kyun Nahi Hota?


Java class-based multiple inheritance allow nahi karta — i.e., ek class ek se zyada classes se
directly inherit nahi kar sakti. Isiliye diamond problem avoid ho jata hai.
class A { void show() {} }
class B extends A {}
class C extends A {}

// Error: class D cannot extend B and C both


class D extends B, C { // Java doesn't allow this
// ...
}

But Interfaces Se Diamond Problem Ho Sakta Hai


Java mein multiple interfaces ko implement kiya ja sakta hai. Tab bhi diamond jaisa
structure banta hai, lekin Java isse handle kar leta hai.

Real Example with Interface:


interface A {
default void show() {
[Link]("A ka show");
}
}

interface B extends A {
default void show() {
[Link]("B ka show");
}
}

interface C extends A {
default void show() {
[Link]("C ka show");
}
}
class D implements B, C {
public void show() {
// Must override to solve ambiguity
[Link](); // Or [Link]();
}
}

Output:
C ka show

Java force karta hai D class ko show() override karne ke लिए ताकक ambiguity clear ho jaaye.

Real-Life Analogy:

मान िो तुम्हारे दो teachers हैं — एक ने कहा “Project Monday ko submit karo” और दस


ू रे
ने कहा “Wednesday ko submit karo”.

अब tum confuse ho jaoge ki kiski suno?

Lekin agar principal (Java) bol de ki tumhe final decision lena padega, to tum decide karoge
ki kis teacher ka instruction follow karna hai — wahi Java mein override karna hota है।

Summary

Point Explanation

Diamond Problem Ambiguity due to multiple inheritance

Java allows multiple classes? No (avoids diamond problem at class level)

Java allows multiple


Yes
interfaces?

By forcing child class to override conflicting methods from


How Java solves it?
interfaces
Q.7 What is the difference between local and instance variables in
Java?
Ans: Java में local variable और instance variable दोनों ही variables होते हैं, िेककन दोनों का
scope, lifetime, और usage अिग-अिग होता है । चिो detail में Hinglish में समझते हैं, साथ
में real-life example भी दे खते हैं

1. Local Variable (स्थानीय चर)

Definition:

Local variable वो variable होता है िो ककसी method, constructor, या block के अंदर declare
ककया िाता है।
इसका scope (area of access) लसर्फ उसी block तक सीलमत होता है ।

Key Points:

• यह लसर्फ उसी method/block के अंदर काम करता है।

• Java compiler default value assign नह ं करता, इसलिए use करने से पहिे initialize
करना ज़रूरी है।

• ये memory में लसर्फ method call होने पर आता है और method के ख़त्म होते ही
गायब हो िाता है।

Real-Life Example:

मान िो आप ककसी restaurant में िाते हो और waiter आपको एक table number दे ता है


(temporary), िैसे ही आप ननकिते हो, वो table number system से delete हो िाता है ।
यानी temporary info — लसर्फ उसी समय के लिए।

Java Example:
public class LocalExample {
public void display() {
int age = 25; // local variable
[Link]("Age is: " + age);
}
}

Outside Access:
public void show() {

[Link](age); // Error - age is not defined here


}

2. Instance Variable (इंस्टें स चर)

Definition:

Instance variable class के अंदर िेककन ककसी method के बाहर declare ककया िाता है। यह
class के हर object के लिए अिग-अिग value रखता है।

Key Points:

• हर object का अपना अिग instance variable होता है ।

• यह class के अंदर होता है और memory तब लमिती है िब object बनाया िाता है ।

• Java automatically default values assign करता है (e.g., int = 0, boolean = false, etc.)

Real-Life Example:

मान िो आप एक school में कई students का record रख रहे हो — हर student का नाम,


रोि नंबर अिग होता है ।
ये सारे values हर object (student) के साथ िड
ु े होते हैं — ये instance variables होते हैं।

Java Example:
public class Student {
String name; // instance variable
int rollNumber; // instance variable
public void show() {
[Link]("Name: " + name);
[Link]("Roll No: " + rollNumber);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
[Link] = "Shrikant";
[Link] = 101;
[Link](); // Output: Shrikant, 101
}
}

Difference Table: Local vs Instance Variables

Feature Local Variable Instance Variable

Scope Method/Block के अंदर परू ी class में , object के साथ

Declare कहााँ करते


Method या block के अंदर Class के अंदर, methods के बाहर
हैं?

नहीं लमिती (initialize करना लमिती है (int=0, boolean=false


Default Value
पडता है ) etc.)

Lifetime Method के ख़त्म होते ही खत्म Object के रहने तक रहता है

Memory कब बनती
Method call पर Object बनते ही
है ?

String name; (inside class, outside


Example int x = 10; (inside method)
method)

Bonus: एक Combined Java Code

public class Example {


int instanceVar = 50; // instance variable
public void method() {
int localVar = 10; // local variable
[Link]("Local: " + localVar);
[Link]("Instance: " + instanceVar);
}
public static void main(String[] args) {
Example ex = new Example();
[Link]();
}
}

Q.8 What is a Marker interface in Java?


Ans: Definition:

Marker Interface एक ऐसी interface होती है जिसमें कोई method नहीं होता — मतिब it's
empty.

इसका काम है लसर्फ एक tag या signal दे ना कक िो class इसे implement कर रही है , उसमें
कुछ special capability है ।

Java में कुछ predefined marker interfaces:

• Serializable
• Cloneable
• Remote
• RandomAccess

Purpose of Marker Interface:

• यह JVM या Java Frameworks को signal करता है कक ककसी object के साथ कोई


special treatment ककया िाना चादहए।

• Compiler या JVM runtime पर check करता है कक क्या class ने marker interface


implement ककया है।

Real-Life Example (Hinglish):


मान िो तुम्हारे पास एक club है जिसमें V.I.P. members के लिए entry free है ।
अब हर visitor की entry पर checking होती है , पर अगर उनके पास "VIP Card" है (जिसमें
कुछ लिखा नहीं होता, बस ददखाना होता है ), तो security बबना question पूछे उन्हें अंदर भेि
दे ती है ।

Exactly यही काम Marker Interface करती है — काम कुछ नहीं करती, पर signal दे ती है !

Java Example: Serializable Marker Interface

Step: Create a class that implements Serializable


import [Link];
public class Student implements Serializable {
int id;
String name;
public Student(int id, String name) {
[Link] = id;
[Link] = name;
}
}

Step: Serialize the object


import [Link];
import [Link];
public class SaveStudent {
public static void main(String[] args) throws Exception {
Student s = new Student(1, "Shrikant");
FileOutputStream fileOut = new FileOutputStream("[Link]");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
[Link](s); // Allowed only because Student is Serializable
[Link]();
[Link]();
[Link]("Object saved successfully!");
}
}

अगर तुम Serializable interface implement नहीं करते, तो writeObject() पर runtime error
आएगा:
[Link]

Custom Marker Interface बनाना

Step 1: Create Empty Interface


interface ImportantData {} // Marker interface
Step 2: Use it in a class
class Employee implements ImportantData {
String name;
public Employee(String name) {
[Link] = name;
}
}
Step 3: Runtime check (Signal)
public class Main {
public static void main(String[] args) {
Employee emp = new Employee("Shrikant");
if (emp instanceof ImportantData) {

[Link]("Send this data to secure server ");


} else {
[Link]("Normal processing");
}
}
}
Use Case Summary:

Interface Purpose

Serializable Object can be saved in file / transferred over network

Cloneable Object can be cloned using clone() method

Remote Object can be accessed remotely (RMI)

Conclusion:

Marker Interface is like a VIP pass — कोई method नहीं, पर उसके होने से system को पता
चिता है कक उसे object को अिग तरीके से handle करना है ।

(Data Structures and Algorithms:)

Q.1 Why are strings immutable in Java?


Ans: "Immutable" का मतिब होता है — "िो बदि नहीं सकता"।

Java में िब हम कहते हैं कक String immutable है , इसका मतिब यह है कक:

एक बार String object create हो िाने के बाद उसकी value को बदिा नहीं िा सकता।

अगर तुम उसे modify करने की कोलशश करते हो, तो Java एक नया String object बना दे ता
है , और परु ाना object वैसा का वैसा ही रहता है।

अब सवाि ये उठता है — ऐसा क्य?ूाँ

Reason 1: Security

बहुत सारी Java classes िैसे URL, File, Database connections आदद Strings पर ननभफर
करती हैं।
अगर कोई malicious code String को change कर दे , तो serious security issue हो सकता है ।

Example:
String url = "jdbc:mysql://localhost:3306/mydb";
// अगर कोई code इस String को change कर दे तो database hack हो सकता है

Reason 2: String Pool (Memory Efficiency)

Java में String Pool होता है , िहााँ एक ही string को कई बार reuse ककया िाता है ।

कैसे?

String s1 = "Shrikant";
String s2 = "Shrikant";

दोनों variable एक ही memory location को point करते हैं — because of immutability!

अगर Strings mutable होते, तो एक की value बदिने से दस


ू रा भी बदि िाता — जिससे
confusion और bugs आते।

Reason 3: Thread Safety


Immutability ensures that multiple threads can safely use the same String without
synchronization.

Example:
Thread 1: reads "Hello"
Thread 2: reads "Hello"

दोनों thread एक ही "Hello" string को बबना ककसी िडाई के access कर सकते हैं।

Reason 4: Hashcode Caching (Performance Boost)

Java में Strings का hashCode() बहुत बार use होता है — िैसे HashMap में keys के तौर पर।

Immutability ensures कक hashCode हमेशा same रहेगा।

सोचो:

अगर string mutable होती, तो पहिे hashCode कुछ और होता, बाद में कुछ और — जिससे
data structures crash कर सकते थे।
Real-Life Example: PAN Card

मान िो तुम्हारा PAN card number है :

String pan = "ABCDE1234F";

अब:

• यह govt द्वारा assigned है ।

• तुम इसे change नहीं कर सकते।

• इसे कई िगह use ककया िाता है (bank, form, tax return आदद)।

PAN number की तरह ही, Java में String once assigned — cannot be changed.

िेककन अगर हमें value change करनी है ?

Use this:
String name = "Shrikant";

name = name + " Kumar"; // ये actually नया object बना रहा है !

अगर frequent changes करनी हों, तो use:

StringBuilder sb = new StringBuilder("Shrikant");

[Link](" Kumar"); // efficient, mutable

Conclusion:

Strings को immutable बनाकर Java:

• Memory बचाता है

• Performance बढ़ाता है

• Bugs और security risks कम करता है

• Multithreading को safe बनाता है


Q.2 What is the difference between creating a String using new()
and as a literal?
Ans: Java में String को दो तरीकों से create ककया िा सकता है:
1. String Literal

String s1 = "Shrikant";

2. Using new Keyword

String s2 = new String("Shrikant");

Detailed Difference

Feature String Literal new String()

Memory Java के String Pool में बनता है (Heap का हमेशा Heap memory में नया
Location दहस्सा) object बनता है

अगर pool में वही string पहिे से है , तो वही हर बार नया object बनता है ,
Duplicates
refer होता है (duplicate नहीं बनता) चाहे value same हो

Comparatively slow and


Performance Fast and memory-efficient
memory-consuming

Comparison Pool में होने से, same literals एक ही new से बने string का
(==) reference दे ते हैं reference अिग होता है

Real-Life Analogy:

String Literal:

मान िो तुम classroom में एक pen मांगते हो और कोई कहता है :


"Mujhe blue pen chahiye."
अगर ककसी के पास पहिे से blue pen है , तो वही दे ददया िाएगा — duplicate pen नह ं बनाया
जाएगा।

Same reference used if available.


new String():

अब सोचो कोई कहता है :


"Mujhe blue pen chahiye, par mujhe naya chahiye."
इस case में , भिे ही ककसी के पास already pen हो, नया pen market से खर दा जाएगा।

New object banega even if same content already exists.

Java Code Example (With Output):

public class StringExample {

public static void main(String[] args) {

String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");

[Link](s1 == s2); // true (same pool reference)


[Link](s1 == s3); // false (heap object, different reference)

[Link]([Link](s3)); // true (content same)


}

Output:
true

false

true

Summary in Hinglish:

• "Java" → ek literal hai, memory-efficient hota hai, and JVM use String pool
mein store karta hai.

• new String("Java") → har baar naya object banata hai (even if same content
ho), so it's less efficient.
• Use String literal jab bhi possible ho — performance better milega.

• == checks reference, .equals() checks content.

Q.3 What is the Collections framework?


Ans: Java में Collections Framework एक ऐसा architecture (ढांचा) है िो objects के group को
store, access, और manipulate करने के लिए तैयार ककया गया है ।

इसमें interfaces, classes, और algorithms का एक set होता है िो डेटा को efficiently


manage करने में मदद करता है।

Simple Definition:
Java Collections Framework ek predefined set of classes and interfaces hai jo humein data
structures jaise List, Set, Map ko use karne ka ready-made tareeka deta hai, bina khud se
logic likhne ke.

Real Life Example:

Imagine karo tumhare पास almaris (almirahs) हैं:

• एक almirah line में books रखने के लिए ( List)

• दस
ू री almirah जिसमें unique keys िाला सामान रखा जाता है , िैसे आधार काडफ नंबर
(🗂 Set)

• तीसरी almirah जिसमें नाम और उसके details stored होते हैं ( Map)

हर almirah का अपना तरीका है चीिें रखने और ननकािने का — Java Collections


Framework इन almirahs (structures) को efficiently manage करता है ।

Components of Java Collections Framework:


Component
Examples Purpose
Type

Blueprint jaisa hota hai (define karta


Interfaces List, Set, Map, Queue
hai kya hona chahiye)

ArrayList, HashSet, HashMap,


Classes Inhe directly use karte hain
LinkedList, PriorityQueue

Data pe operations perform karne ke


Algorithms [Link](), shuffle(), reverse()
liye

Major Interfaces and Classes:


1. List (Ordered collection with duplicates allowed)
• Classes: ArrayList, LinkedList, Vector
• Use Case: Students ke roll numbers jisme duplicate allowed hai
List<String> names = new ArrayList<>();
[Link]("Shrikant");
[Link]("Mansi");
[Link]("Shrikant"); // allowed

2. Set (No duplicates allowed)


• Classes: HashSet, LinkedHashSet, TreeSet
• Use Case: Aadhaar numbers — unique hone chahiye
Set<Integer> aadhaarSet = new HashSet<>();
[Link](1234);
[Link](1234); // ignored

3. Map (Key-Value pair)


• Classes: HashMap, TreeMap, LinkedHashMap
• Use Case: Student name and their marks
Map<String, Integer> marks = new HashMap<>();
[Link]("Shrikant", 90);
[Link]("Mansi", 95);

4. Queue (FIFO)
• Classes: PriorityQueue, LinkedList
• Use Case: Bank ki line – pehle aaya, pehle jaayega
Queue<String> line = new LinkedList<>();
[Link]("Person1");
[Link]("Person2");
[Link]([Link]()); // Person1

Algorithms (Collections Class ke methods)


• sort(), reverse(), shuffle(), min(), max(), etc.
[Link](names); // names ko sort karega
[Link](names);

Why Use Collections Framework?

Readymade and optimized data structures


Code reusability & consistency
Fast searching/sorting
Thread-safe classes (like Vector)
Less coding effort

Summary :

Feature Description

क्या है ? (What) Java ka ek powerful toolset jo groups of objects ko handle karta hai

क्यों ज़रूरी है ? (Why) Data manage karna easy, fast aur reusable banata hai

कौन-कौन से टूल्स? List, Set, Map, Queue, ArrayList, HashSet, HashMap, LinkedList, etc.

Algorithms Sorting, Searching, Reversing, etc. using Collections class


Example (Real World)

मान िो तुम एक Coaching Center चिा रहे हो — तुम्हें Students की list, उनके unique IDs,
और उनके test scores को track करना है।

• Students की list: List<String>

• IDs (no duplicate): Set<Integer>


• Name and Score: Map<String, Integer>

Q.4 What is the difference between ArrayList and LinkedList?


Ans: Java में ArrayList और LinkedList दोनों ही List interface को implement करते हैं और
collection of elements को store करने के लिए use होते हैं। िेककन इनके पीछे की
implementation, performance, और use cases अिग होते हैं।

1. Basic Structure

Feature ArrayList LinkedList

Structure Dynamic array पर आधाररत Doubly linked list पर आधाररत

Internal Memory एक continuous memory block Nodes में memory scattered होती है

Real-Life Example:

• ArrayList — िैसे एक cinema hall में numbered seats हों (िैसे row A1, A2, A3...) —
सभी एक line में fixed होती हैं।

• LinkedList — िैसे एक train की bogies — हर bogie अगिे से िुडी होती है , और बीच में
िोडना/हटाना आसान है ।

Example:

• अगर आपको कोई list बनानी है िहााँ से बार-बार हटाना या जोड़ना है — तो LinkedList
बेहतर।

• िेककन अगर आपको बार-बार access करना है (िैसे index से), तो ArrayList तेज़ है।
3. Memory Usage

• ArrayList contiguous memory block िेती है।

• LinkedList हर node के साथ extra memory (next और previous pointers) िेती है ।

Real-Life Analogy:

• ArrayList = एक bookshelf, जिसमें books एक के बाद एक सीधी line में रखी िाती हैं।

• LinkedList = एक chain of keys, जिसमें हर key अगिी key से िुडी होती है ।

Java Example Code


import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
// ArrayList
ArrayList<String> arrayList = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");
[Link]("ArrayList: " + arrayList);

// LinkedList
LinkedList<String> linkedList = new LinkedList<>();
[Link]("Car");
[Link]("Bike");
[Link]("Bus");
[Link]("LinkedList: " + linkedList);
}
}
कब क्या Use करें ?

Situation Use This

Frequent access by index ArrayList

Frequent insertion/deletion
LinkedList

Memory efficiency is important ArrayList

Doubly linked data structure needed


LinkedList

Q.5 What is the difference between a HashMap and a


TreeMap?
Ans: Java में HashMap और TreeMap दोनों ही Map interface को implement करते हैं, िेककन
इनके बीच कुछ महत्वपूर्फ अंतर होते हैं — िैसे ordering, performance, null keys/values,
आदद।

1. Ordering (क्रम)

HashMap:

• No ordering guarantee दे ता है — मतिब data ककस order में store या retrieve होगा,
यह fix नहीं होता।

TreeMap:

• Keys को sorted order (ascending) में रखता है (natural order या custom comparator
के दहसाब से)।

Real-Life Example:

• HashMap = िैसे एक डायर में random जगहों पर नोट्स शलखना।

• TreeMap = िैसे alphabetical index में notes रखना (A-Z sorted)।


• 2. Performance (Speed)
• HashMap बहुत तेज़ है क्योंकक यह hashing use करता है ।
TreeMap थोडा slow होता है क्योंकक यह Red-Black Tree data structure पर काम
करता है ।

• Syntax Example:
• HashMap Example:

• import [Link].*;

• public class HashMapExample {
• public static void main(String[] args) {
• HashMap<String, Integer> map = new HashMap<>();

• [Link]("Apple", 50);
• [Link]("Banana", 30);
• [Link]("Mango", 70);

• [Link](map);
• }
• }

• Output (order not guaranteed):
• {Mango=70, Banana=30, Apple=50}


• TreeMap Example:
• import [Link].*;

• public class TreeMapExample {
• public static void main(String[] args) {
• TreeMap<String, Integer> map = new TreeMap<>();

• [Link]("Apple", 50);
• [Link]("Banana", 30);
• [Link]("Mango", 70);

• [Link](map);
• }
• }
• Output (sorted by key):

• {Apple=50, Banana=30, Mango=70}
• Real-Life Example:
• HashMap:
• मान िो तुमने grocery items को product ID से store ककया — तुम्हें बस fast
lookup चादहए, order से कोई मतिब नहीं।

• HashMap<Integer, String> grocery = new HashMap<>();
• [Link](101, "Milk");
• [Link](205, "Eggs");
• [Link](110, "Bread");

• TreeMap:
• मान िो तुमने student names को roll number के साथ alphabetically store
करना है।
• TreeMap<String, Integer> students = new TreeMap<>();
• [Link]("Amit", 1);
• [Link]("Ravi", 2);
• [Link]("Karan", 3);
• Output:

• {Amit=1, Karan=3, Ravi=2}

Q.6 What is the difference between a HashSet and a TreeSet?


Ans: Java में HashSet और TreeSet दोनोों ही Set interface को implement करते हैं — यानी दोनोों
में duplicate elements store नहीों ककए जा सकते। लेककन इन दोनोों के बीच कुछ important
differences होते हैं ।

1. Ordering (क्रम)

HashSet:

• Elements को unordered तरीके से store करता है ।


• मतलब कजस order में आप data डालते हो, उस order में वापस नहीों कमलेगा।

TreeSet:

• Elements को sorted (natural order) में store करता है ।


• जैसे numbers ascending order में या strings alphabetically.

Real-life Example:

• HashSet = जैसे एक थैली में coins डाल दे ना – कोई क्रम नहीों।


• TreeSet = जैसे coins को value के अनुसार arrange करना (₹1, ₹2, ₹5...)

🛠 Real-life Use Cases:

HashSet:

जब आपको fast lookup चाकहए और order से मतलब नहीों है ।


Example:

• Track करना कक कौन से students ने assignment submit ककया है ।


• Check करना कक एक mobile number पहले से registered है या नहीों।

TreeSet:

जब आपको elements को sorted form में store करना है।


Example:

• Store करना कक कौन-कौन से usernames system में हैं – और alphabetically show करना है।
• Leaderboard या score list में players को sort करना।

Example: HashSet

import [Link].*;

public class HashSetExample {

public static void main(String[] args) {

HashSet<String> fruits = new HashSet<>();

[Link]("Apple");

[Link]("Mango");

[Link]("Banana");

[Link]("Apple"); // Duplicate
[Link](fruits);

Output:

[Banana, Apple, Mango]

Note: Order is not guaranteed, and "Apple" is added only once.

Example: TreeSet

import [Link].*;

public class TreeSetExample {

public static void main(String[] args) {

TreeSet<String> fruits = new TreeSet<>();

[Link]("Apple");

[Link]("Mango");

[Link]("Banana");

[Link]("Apple"); // Duplicate

[Link](fruits);

Output:

[Apple, Banana, Mango]


Q.7 What is the difference between an Iterator and a ListIterator?
Ans: Java में Iterator और ListIterator दोनोों ही interfaces हैं जो collections को traverse
(iterate) करने के कलए use होते हैं।

Iterator:

• यह कसर्फ आगे (forward) direction में चलता है ।


• यह सभी Collection classes (List, Set, Queue) के कलए use हो सकता है ।
• इसमें कसर्फ remove() method होता है ।

Iterator<Type> it = [Link]();

ListIterator:

• यह आगे (forward) और पीछे (backward) दोनोों directions में चल सकता है ।


• यह कसर्फ List interface की classes (जैसे ArrayList, LinkedList) के कलए होता है ।
• इसमें add(), set(), remove() — तीनोों methods available होते हैं ।

ListIterator<Type> lit = [Link]();

Code Example

Using Iterator:

import [Link].*;

public class IteratorExample {

public static void main(String[] args) {

List<String> fruits = new ArrayList<>([Link]("Apple", "Banana", "Mango"));

Iterator<String> it = [Link]();

while ([Link]()) {

String fruit = [Link]();

[Link](fruit);

}
}

Output:

Apple

Banana

Mango

यह कसर्फ आगे की direction में चल रहा है ।

Using ListIterator (Bidirectional):

import [Link].*;

public class ListIteratorExample {

public static void main(String[] args) {

List<String> fruits = new ArrayList<>([Link]("Apple", "Banana", "Mango"));

ListIterator<String> lit = [Link]();

[Link]("Forward Traversal:");

while ([Link]()) {

[Link]([Link]());

[Link]("\nBackward Traversal:");

while ([Link]()) {

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

Output:

Forward Traversal:

Apple

Banana

Mango

Backward Traversal:

Mango

Banana

Apple

यहााँ ListIterator दोनोों directions में चल रहा है ।

Methods Comparison:

Method Iterator ListIterator


hasNext()
next()
hasPrevious()
previous()
remove()
add()
set()

🛠 Real-Life Analogy:

Iterator:
जैसे तुम एक one-way सड़क पर चल रहे हो — बस आगे बढ़ सकते हो, पीछे नहीों दे ख सकते।

ListIterator:

जैसे तुम दो-तरफा सड़क पर हो — तुम आगे भी जा सकते हो, पीछे भी आ सकते हो, रास्ते में कुछ
जोड़ या बदल भी सकते हो।

Q.8 What is the purpose of the Comparable interface?

Ans: Purpose:

Java में Comparable interface का इस्तेमाल objects को naturally sort करने के कलए ककया
जाता है ।
जब आप ककसी class के objects को [Link]() या [Link]() से sort करना चाहते हैं ,
तो Java को यह जानना ज़रूरी है कक दो objects को compare कैसे करना है — यही काम
Comparable करता है।

Definition:

Comparable interface कसर्फ एक method दे ता है :

public interface Comparable<T> {

public int compareTo(T o);

• compareTo() method define करता है कक:


o कोई object दू सरे से छोटा है (return < 0)
o बराबर है (return 0)
o या बड़ा है (return > 0)

Real-Life Example Analogy:

Socho tumhare paas student ki list hai, aur tum unhe marks ke कहसाब से sort करना चाहते
हो।

Tum Java को ये खुद बताओगे ki Student class के objects को कैसे compare करना है — marks के
base पर — तभी Java उसे sort कर पाएगा।
Example Code:

Step 1: Create Student Class implementing Comparable

class Student implements Comparable<Student> {

String name;

int marks;

Student(String name, int marks) {

[Link] = name;

[Link] = marks;

// Comparable method

public int compareTo(Student s) {

return [Link] - [Link]; // Ascending order by marks

public String toString() {

return name + " - " + marks;

Step 2: Sort the list of Students

import [Link].*;

public class Main {

public static void main(String[] args) {

List<Student> students = new ArrayList<>();

[Link](new Student("Ravi", 85));

[Link](new Student("Amit", 92));


[Link](new Student("Sneha", 78));

[Link](students); // Uses compareTo()

for (Student s : students) {

[Link](s);

Output:

Sneha - 78

Ravi - 85

Amit - 92

ये sorting marks के कहसाब से हुई है क्ोोंकक हमने compareTo() में वही logic कलखा है ।

Q.9 What is the purpose of the [Link] package?


Ans: [Link] package का purpose multi-threading को आसान, सुरक्षित और
efficient बनाना है — ताकक हम multiple threads को एक साथ run करवा सकें बबना race
conditions, deadlocks या synchronization errors के।

Purpose of [Link] Package

1. Thread-safe data structures

• जैसे: ConcurrentHashMap, CopyOnWriteArrayList, etc.


• ये structures multiple threads को एक साथ access करने दे ते हैं बिना error के।
2. Thread pooling

• जैसे: ExecutorService, ThreadPoolExecutor


• New thread बार-बार create करने की बजाय existing thread pool का use करता है , कजससे
performance improve होती है ।

3. Synchronization utilities

• जैसे: Semaphore, CountDownLatch, CyclicBarrier, Lock, etc.


• यह thread coordination में मदद करते हैं — कौन thread पहले execute होगा, कौन wait
करे गा, etc.

4. Atomic variables

• जैसे: AtomicInteger, AtomicBoolean


• ये variables multiple threads में safely update ककए जा सकते हैं बिना explicit
synchronization के।

5. Callable and Future

• यह हमें allow करता है कक हम thread से value return करवा सकें और result को future में
retrieve कर सकें।

Real-Life Analogy

Imagine एक pizza shop है :

• Customers = Threads
• Pizza makers = CPU/Core
• Orders = Tasks

Old way (Thread manually):

हर order के कलए नया worker hire करते हो → slow and costly.

New way (ExecutorService):

एक fixed staff है जो सारे orders efficiently complete करता है — यही काम [Link]
करता है !

Example 1: Using ExecutorService (Thread Pool)


import [Link].*;

public class PizzaShop {

public static void main(String[] args) {

ExecutorService executor = [Link](3);

Runnable order1 = () -> [Link]("Preparing Order 1");

Runnable order2 = () -> [Link]("Preparing Order 2");

Runnable order3 = () -> [Link]("Preparing Order 3");

Runnable order4 = () -> [Link]("Preparing Order 4");

[Link](order1);

[Link](order2);

[Link](order3);

[Link](order4);

[Link](); // Stop accepting new tasks

Output (may vary):

Preparing Order 1

Preparing Order 2

Preparing Order 3

Preparing Order 4

Note: At a time, only 3 threads work because pool size = 3


Example 2: Callable and Future (Return value from thread)

import [Link].*;

public class ReturnValueExample {

public static void main(String[] args) throws Exception {

ExecutorService service = [Link]();

Callable<String> task = () -> {

[Link](2000); // simulating time-consuming task

return "Pizza is ready!";

};

Future<String> future = [Link](task);

[Link]("Order placed, waiting...");

String result = [Link](); // blocks until result is available

[Link](result);

[Link]();

Output:

Order placed, waiting...


Pizza is ready!

Example 3: ConcurrentHashMap — Safe shared data access

import [Link].*;

public class SafeMapExample {

public static void main(String[] args) {

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

Runnable task1 = () -> [Link]("Thread1", 1);

Runnable task2 = () -> [Link]("Thread2", 2);

new Thread(task1).start();

new Thread(task2).start();

try { [Link](100); } catch (InterruptedException e) {}

[Link](map);

Summary Table:

Feature Description
Thread Pooling Efficient reuse of threads (ExecutorService)
Task Result Use Callable and Future
Thread-safe Collections ConcurrentHashMap, CopyOnWriteArrayList
Atomic Variables AtomicInteger, AtomicLong for safe counters
Synchronization Tools Semaphore, CountDownLatch, ReentrantLock etc.
(Exception Handling:)

Q.1 What is an exception?


Ans: Java में Exception एक ऐसा concept है िो हमें run time errors को handle करने का
तरीका दे ता है ताकक program अचानक crash न हो िाए। इसे हम error handling
mechanism भी कहते हैं।

What is an Exception in Java?

Definition:

Exception ek "abnormal condition" hai jo program ke normal flow ko disturb karti hai.
Jab program mein koi error aata hai (jaise division by zero, file not found, array out of
bounds), tab Java ek Exception Object throw karta hai.

Example (Real Life Analogy):

Sochiye aap ek ATM machine use kar rahe ho.

• Aap ₹1000 कनकालना चाहते हो लेककन account में कसर्फ ₹500 हैं ।
ये ek exceptional condition hai.

Java mein bhi jab koi situation aati hai jo unexpected hoti hai (jaise kisi file ko read karna jo
exist hi nahi karti), tab exception aata hai.

Types of Exceptions in Java

Java mein exceptions do category ke hote hain:

Type Explanation
Checked Compile-time pe handle karna mandatory hai (e.g.,
Exception FileNotFoundException)

Unchecked Run-time pe aate hain, aur handle karna programmer ke upar hota hai
Exception (e.g., ArithmeticException, NullPointerException)

Exception Handling in Java:


Java mein exceptions ko handle karne ke liye hum try, catch, finally, aur throw/throws use
karte hain.

Syntax:

try {

// Risky code yahan likhte hain

} catch (ExceptionType e) {

// Exception handle karte hain

} finally {

// Yeh hamesha chalega, chahe exception aaye ya nahi

Real Code Example:

public class ExceptionExample {

public static void main(String[] args) {

try {

int a = 10, b = 0;

int result = a / b; // yeh ArithmeticException throw karega

[Link]("Result: " + result);

} catch (ArithmeticException e) {

[Link]("Error: Divide by zero is not allowed.");

} finally {

[Link]("Program execution complete.");

}}}

Output:

Error: Divide by zero is not allowed.

Program execution complete.


Q.2 How does an exception propagate throughout the Java code?
Ans: Java में जब कोई exception (अपवाद) आता है, तो वह method call stack के ज़ररए
"propagate" होता है — यानी अगर ककसी method में exception handle नहीों हुआ, तो वो अगले
caller method तक चला जाता है , और ऐसा तब तक होता है जब तक उसे handle कर कलया जाए या
program crash हो जाए।

Basic Concept: Exception Propagation in Java

Rule:

Agar ek method me exception aata hai aur try-catch block nahi hai, to exception caller
method tak propagate karta hai.

Agar kahin bhi exception handle nahi hota:

Java Runtime system program ko terminate kar deta hai aur stack trace show karta hai.

Propagation Flow

method1() {

method2(); // called method

method2() {

method3(); // called method

method3() {

int a = 10 / 0; // ArithmeticException

➡ method3() में exception आया


➡ method3 ने handle नहीों ककया ➝ propagate हुआ method2() में
➡ method2() ने भी handle नहीों ककया ➝ propagate हुआ method1() में
➡ method1() ने भी handle नहीों ककया ➝ program crash हो गया
Real-Life Example:

Scenario:

मान लो तुमने एक कार चलाई, लेककन उसमें engine fail हो गया।

• Mechanic A (method3) को call ककया — उसने fix नहीों ककया


• कर्र तुमने Supervisor B (method2) को बताया — उसने भी नहीों fix ककया
• कर्र तुम Owner C (method1) के पास पहुाँ चे — अब उसने finally handle ककया या कर्र
कार छोड़ दी

Java Code Example (with Propagation):

public class ExceptionPropagationExample {

void method3() {

// Exception occurs here

int data = 10 / 0;

void method2() {

method3(); // No try-catch here

void method1() {

try {

method2(); // Catching exception here

} catch (ArithmeticException e) {

[Link]("Exception handled in method1: " + e);

}
public static void main(String[] args) {

ExceptionPropagationExample obj = new ExceptionPropagationExample();

obj.method1(); // Start point

Output:

Exception handled in method1: [Link]: / by zero

Flow:

1. method3() → Exception आया (/ by zero)


2. method2() → कोई handling नहीों
3. method1() → catch block है → Exception यही ीं handle हो गया

If No Catch Block:

void method1() {

method2(); // No try-catch

➡ Program crash होगा और output में stack trace कमलेगा:

Exception in thread "main" [Link]: / by zero

at method3()

at method2()

at method1()

at main()

Tip:

Always use try-catch blocks at top level if you can't handle exception in lower-level
methods.
Q.3 What is the difference between checked and unchecked
exceptions?
Ans: 1. Checked Exceptions (Compile-Time Exceptions)

Definition:

• ये वो exceptions होते हैं कजन्हें compile time पर handle करना ज़रूरी होता है।
• अगर आप इन्हें try-catch से handle नहीों करोगे या method में throws keyword से declare
नहीों करोगे, तो compile-time error आएगा।

Real-Life Example:

मान लो आप train से travel कर रहे हो और ticket कदखाना ज़रूरी है। अगर आपके पास ticket नहीों
है , तो आप पहले से aware हो — इसकलए आपको पहले से manage करना पड़े गा (planned
exception handling)।

Example Code:

import [Link].*;

public class CheckedExample {

public static void main(String[] args) {

try {

FileReader file = new FileReader("[Link]"); // file might not exist

} catch (FileNotFoundException e) {

[Link]("File not found: " + e);

यह exception compile time पर check होती है :


FileNotFoundException — इसकलए यह Checked Exception है ।

2. Unchecked Exceptions (Runtime Exceptions)


Definition:

• ये exceptions runtime पर आती हैं और compiler इनकी checking नही ीं करता।


• इन्हें handle करना ज़रूरी नहीों है — आपकी मज़़ी है try-catch लगाओ या नहीों।

Real-Life Example:

मान लो आप बिना दे खे सीढी से उतरते हुए बगर गए — यह अचानक हुआ (unexpected), इसे
compile time पर नहीों detect ककया जा सकता।

Example Code:

public class UncheckedExample {

public static void main(String[] args) {

int a = 10;

int b = 0;

int result = a / b; // ArithmeticException (Divide by zero)

[Link](result);

Output:

Exception in thread "main" [Link]: / by zero

यह error runtime पर आती है — इसकलए यह Unchecked Exception है ।

Q.4 What is the use of try-catch block in Java?

Ans: Java में try-catch block का उपयोग exception handling के कलए ककया जाता है। जब
program में कोई ऐसी गलती (error) आती है कजससे program crash हो सकता है , तब try-catch
block उस error को handle करके program को safely execute करने में मदद करता है ।

Try Block:

• वह block होता है कजसमें हम ऐसा code कलखते हैं कजससे exception (error) आने की
सोंभावना होती है ।
• अगर exception आता है , तो वो catch block को control भेज दे ता है ।

Catch Block:

• यहााँ हम उस exception को handle करते हैं , ताकक program पूरी तरह से crash न हो और
user को proper message कदखाया जा सके।

Real Life Example:

Example Situation:

मान लो तुमने एक calculator app बनाया है और user ने accidentally 0 से divide करने की कोकिि
की:

int result = a / b; // If b = 0, this will cause an exception

इससे program crash हो सकता है ।

Try-Catch Example:

public class TryCatchExample {

public static void main(String[] args) {

int a = 10;

int b = 0;

try {

int result = a / b;

[Link]("Result: " + result);

} catch (ArithmeticException e) {

[Link]("Error: You can't divide by zero.");

[Link]("Program continues...");

}
}

Output:

Error: You can't divide by zero.

Program continues...

अगर हमने try-catch block न लगाया होता, तो program बीच में ही crash हो जाता।

Why Use Try-Catch?

Feature Explanation
Avoid Crash Program crash होने से बचता है
User Friendly Message User को understandable error message कदखा सकते हैं
Safe Execution Program का बाकी कहस्सा कबना रुके चलता है
Debugging Error को log या print कर सकते हैं

Multiple Catch Example:

try {

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

[Link](arr[5]); // ArrayIndexOutOfBoundsException

} catch (ArithmeticException e) {

[Link]("Math error occurred");

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Array index is invalid");

} catch (Exception e) {

[Link]("Something went wrong");

Summary:
• try block में risky code कलखते हैं
• catch block उस error को पकड़कर सही message कदखाता है
• इससे program crash नही ीं होता, smoothly चलता रहता है I

Q.5 What is the difference between throw and throws?


Ans: Java में throw और throws दोनोों exception handling से जुड़े keywords हैं, लेककन इनका
use और meaning अलग-अलग होता है ।

throw vs throws: Basic Difference

Feature throw throws


Manually exception फेंकने Method के साथ बताता है कक वो कौनसी
Purpose
के कलए exception फेंक सकता है
Use Location Method body (अोंदर) Method declaration (signature में)
Throwing a specific
Used For Declaring potential exceptions
exception
Number of
Only one at a time Multiple (comma-separated) possible
Exceptions
throw new returnType methodName() throws
Syntax
ExceptionType(); ExceptionType {}

Real-Life Analogy:

throw:

जैसे कोई आदमी गुस्से में खुद कहता है "मैं resign दे रहा हाँ !" – यानी उसने खुद decision कलया
(exception manually throw की)।

throws:

जैसे कोई employee कहता है , "मैं काम करू ों गा लेककन हो सकता है मुझे छु ट्टी लेनी पड़े " – यानी पहले
ही declare कर रहा है कक future में exception आ सकती है ।

Detailed Example:

Using throw (Manually throw an exception):

public class ThrowExample {

public static void main(String[] args) {


int age = 15;

if (age < 18) {

throw new ArithmeticException("You are not eligible to vote.");

[Link]("You can vote.");

Output:

Exception in thread "main" [Link]: You are not eligible to vote.

Explanation:

• यहाों हम manually check कर रहे हैं और खुद से throw कर रहे हैं ArithmeticException।

Using throws (Declaring a possible exception):

import [Link].*;

public class ThrowsExample {

// method declares it may throw IOException

public static void readFile() throws IOException {

FileReader file = new FileReader("[Link]");

BufferedReader fileInput = new BufferedReader(file);

[Link]([Link]());

[Link]();
}

public static void main(String[] args) throws IOException {

readFile();

Explanation:

• यहाों method ने declare बकया है कक वो IOException र्ेंक सकता है (throws


IOException), लेककन खुद से throw नहीों ककया।

Combined Use:

public class ComboExample {

// throws used in method signature

public static void checkAge(int age) throws ArithmeticException {

if (age < 18) {

// throw used to generate exception

throw new ArithmeticException("Underage not allowed!");

} else {

[Link]("Welcome to the voting system.");

public static void main(String[] args) {

checkAge(16);

}
}

Output:

Exception in thread "main" [Link]: Underage not allowed!

Q.6 What is the use of the finally block?


Ans: Definition :

finally block एक ऐसा block होता है जो try-catch block के बाद कलखा जाता है और ये हर हाल में
चलेगा, चाहे exception हो या न हो, या चाहे exception handle हुआ हो या नहीों।

Syntax:

try {

// Code that may throw exception

} catch (Exception e) {

// Code to handle exception

} finally {

// Code that will always execute

Use of finally block – क्ोीं ज़रूरी है?

1. Resource Cleanup: जैसे files, database connections, memory, network connections को


close करने के कलए।
2. Guaranteed Execution: Program में कोई भी हालत हो, ये block चलेगा ही चलेगा।
3. Avoiding Code Duplication: बार-बार same cleanup code ना कलखना पड़े , इसकलए।

Real-life Analogy:

मान लो तुमने एक ATM machine से पैसे कनकालने की कोकिि की:

• try: Card डालना और पैसे कनकालने की कोकिि।


• catch: अगर कोई error आ जाए (जैसे insufficient balance), तो उसका message कदखाना।
• finally: Card वापस कमलना — हमेशा card तो machine वापस दे ही दे ती है , चाहे transaction
successful हो या नहीों।
Example in Java:

public class FinallyExample {

public static void main(String[] args) {

try {

int num = 10 / 0; // This will throw ArithmeticException

} catch (ArithmeticException e) {

[Link]("Caught an exception: " + e);

} finally {

[Link]("This block always executes (cleanup, close connection,


etc.)");

Output:

Caught an exception: [Link]: / by zero

This block always executes (cleanup, close connection, etc.)

Another Example with File Handling:

import [Link].*;

public class FileReadExample {

public static void main(String[] args) {

BufferedReader br = null;

try {

br = new BufferedReader(new FileReader("[Link]"));

String line = [Link]();

[Link](line);
} catch (IOException e) {

[Link]("File not found or error reading file");

} finally {

try {

if (br != null) [Link](); // Always close the resource

[Link]("File closed successfully");

} catch (IOException e) {

[Link]("Error closing file");

}}}}

Q.7 What’s the base class of all exception classes?


Ans: Java में सभी exception classes की base class होती है → [Link].
Throwable — Base Class of All Errors and Exceptions

Java में error handling के कलए hierarchy इस प्रकार होती है :


Throwable के दो मुख्य subclasses:

1. Exception:

• यह वो conditions होती हैं कजन्हें handle (catch) ककया जा सकता है ।


• जैसे: File not found, Divide by zero, Invalid input, etc.

2. Error:

• यह वो serious problems होती हैं कजन्हें generally handle नही ीं बकया जाता।
• जैसे: OutOfMemoryError, StackOverflowError, JVM crash, etc.

Real-Life Analogy:

Throwable = "सभी problems की जड़"

मान लो आप एक school में principal हैं । अब आपको दो तरह की problems deal करनी पड़ती हैं :

1. Exception (छोटी समस्याएीं ) – जैसे student late आया, homework नहीों ककया। इनको
manage बकया जा सकता है।
2. Error (िड़ी समस्याएीं ) – जैसे school की कबल्डों ग कगर गई या fire लग गई। ये serious हैं
और avoid नही ीं की जा सकती ीं।

तो इन दोनोों problems की "जड़" है Throwable.

Code Structure with Real Example:

public class ThrowableExample {

public static void main(String[] args) {

try {

int a = 10 / 0; // ArithmeticException

} catch (Throwable t) {

[Link]("Caught: " + t);

[Link]("Type: " + [Link]().getName());

}
Q.8 What is Java Enterprise Edition (Java EE)?
Ans: Java EE (अब Jakarta EE) एक platform है जो Java language पर आधाररत है और
enterprise-level applications बनाने के कलए use ककया जाता है ।
यह Java SE (Standard Edition) को extend करता है और enterprise applications जैसे — web
apps, APIs, distributed systems, secure and scalable apps — के development को आसान
बनाता है ।

Full Form:

Java EE = Java Enterprise Edition

अब इसे Jakarta EE कहा जाता है (Oracle से Eclipse Foundation को transfer होने के बाद)।

Java EE में क्ा-क्ा शाबमल होता है?

Java EE में कई built-in APIs और components होते हैं जो हमें ready-made structure दे ते हैं ताकक
हम robust और secure enterprise applications बना सकें।

Major Components / APIs:

Component / API Description


Servlets HTTP request और response handle करने के कलए
JSP (JavaServer Pages) HTML + Java का mix — dynamic web content
EJB (Enterprise JavaBeans) Business logic handle करता है — secure, transactional
Database से interact करने के कलए ORM (Object
JPA (Java Persistence API)
Relational Mapping)
JAX-RS / JAX-WS RESTful और SOAP web services के कलए
Messaging systems के कलए (asynchronous
JMS (Java Message Service)
communication)
CDI (Contexts and Dependency Objects का automatic injection and lifecycle
Injection) management

🏗 Real-Life Analogy:

Java SE vs Java EE:

Scenario Java SE Java EE


Tools जैसे तुमने घर बनाने के कलए कसर्फ जैसे तुमने घर बनाने के कलए full construction
only हथौड़ा और हकथयार कलए team, blueprints, और materials कलए
Scope Desktop apps, basic logic Web apps, online portals, banking, e-commerce
Real-Life Example:

Suppose:

आपको एक Online Banking System बनाना है कजसमें िाकमल हैं :

• User Login (Servlet)


• Balance Check (EJB)
• Fund Transfer (EJB + Transaction)
• Statement Download (JSP)
• Notification via Email/SMS (JMS)
• REST API for Mobile App (JAX-RS)
• Database storage (JPA)

Java EE ये सारी चीजें provide करता है through different APIs — और वो भी standardized


तरीके से।

Example Code Snippet (Servlet):

@WebServlet("/hello")

public class HelloServlet extends HttpServlet {

protected void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

[Link]().write("Hello from Java EE!");

Benefits of Java EE (Jakarta EE):

1. Reusable components – जैसे Servlets, Beans, etc.


2. Scalability – बढ़ते users के कलए easily scale ककया जा सकता है ।
3. Security – Built-in authentication and authorization.
4. Platform Independent – Java Virtual Machine पर चलता है ।
5. Standardization – एक standard architecture provide करता है large applications के
कलए।
Q.9 What is the difference between a Servlet and a JSP?
Ans: Java में Servlet और JSP (Java Server Pages) दोनोों server-side technologies हैं, जो
dynamic web content (जैसे HTML pages with data) generate करने के कलए use होती हैं । लेककन
इनके बीच उपयोग, सोंरचना (structure), और control flow के मामले में कार्ी र्कफ होता है ।

1. Basic Definition

Servlet:

• Java classes होती हैं जो HTTP requests को handle करती हैं और responses दे ती हैं ।
• Purely Java code होता है ।
• ज्यादा suitable है business logic और controller logic के कलए।

JSP (Java Server Pages):

• HTML के साथ embedded Java code होता है ।


• HTML कलखना easy होता है , Java code बीच में आता है ।
• ज्यादा suitable है presentation logic के कलए (याकन जो user को कदखाई दे ता है )।

🛠 Structure (Code Writing Style):

Feature Servlet JSP


Language Pure Java HTML + Java
Extension .java (compiled to .class) .jsp (converted to Servlet internally)
Who writes more HTML? Less (harder) More (easier for designers)
Who writes more Java? More Less (minimal Java code preferred)

Real-Life Analogy:

Imagine you're running a restaurant.

Servlet = Chef

• Chef prepares food in the kitchen (backend).


• He knows all the logic: what ingredients, how to cook, etc.
• But doesn't serve directly to the customer.

JSP = Waiter with Menu

• Waiter shows a nice menu (presentation).


• Takes orders and shows formatted content.
• Doesn’t do the cooking, but displays it in a nice way.

So:
• Servlet = Logic और data handle करता है ।
• JSP = उसे nicely format करके client को कदखाता है ।

Servlet Example:

@WebServlet("/hello")

public class HelloServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<h1>Hello from Servlet</h1>");

Disadvantage: HTML code Java के अोंदर कलखना पड़ता है , जो messy हो जाता है ।

JSP Example:

<%@ page language="java" contentType="text/html" %>

<html>

<head><title>Hello JSP</title></head>

<body>

<h1>Hello from JSP</h1>

<%

String name = "Shrikant";

[Link]("Welcome " + name);

%>

</body>

</html>
Q.10 What is the purpose of the Java Persistence API (JPA)

Ans: Java Persistence API (JPA) एक Java specification है जो हमें Java objects को relational
database (जैसे MySQL, Oracle, PostgreSQL) में store (save), update, delete, और retrieve
करने की सुकवधा दे ती है — बिना SQL queries manually बलखे।

What is JPA?

• JPA = Java Persistence API


• यह एक specification (interface) है , implementation नहीों।
• इसे implement करने वाले tools हैं :
o Hibernate (सिसे popular)
o EclipseLink
o OpenJPA, etc.

JPA का काम है :
Java classes को database की tables से map करना
Java objects को database में auto-manage करना

Purpose of JPA (Kya kaam karta hai?)

1. ORM (Object Relational Mapping):

• JPA Java class को table में convert करता है (और vice versa).
• हर Java class = 1 table
• हर Java object = 1 row
• हर field = 1 column

2. SQL से छु टकारा बदलाता है:

• हमें SQL queries manually likhne की जरूरत नहीों पड़ती।


• Instead, हम Java code से hi data save/fetch कर सकते हैं ।

3. Database Independent िनाता है:

• एक बार JPA code कलखा तो वो MySQL, PostgreSQL, Oracle जैसे ककसी भी DB के साथ
काम कर सकता है (just change config).

4. Automatic Transactions, Lazy Loading, Caching:

• Complex DB operations को JPA automatically manage करता है .


Real-Life Example (Student Management)

Step 1: Entity Class

import [Link].*;

@Entity

@Table(name = "students")

public class Student {

@Id

@GeneratedValue(strategy = [Link])

private int id;

@Column(name = "student_name")

private String name;

private int marks;

// Getters & Setters

यहााँ @Entity से बताया कक ये class database table से map होगी


@Id = primary key
@Column = table का column

Step 2: Save data in DB (No SQL needed)

EntityManagerFactory emf = [Link]("myunit");

EntityManager em = [Link]();
Student s = new Student();

[Link]("Shrikant");

[Link](85);

[Link]().begin();

[Link](s); // Data save ho gaya DB mein

[Link]().commit();

[Link]();

Output: DB में एक row insert हो जाएगी bina SQL likhe

Step 3: Retrieve data

Student s = [Link]([Link], 1); // roll number 1 ka student fetch karo

[Link]([Link]());

Real-life Analogy:

मान लो आपके पास एक student record register है — हर student की entry उस register में होती
है ।

Without JPA:

• हर बार record insert/update/delete करने के कलए आपको manually SQL likhna पड़ता है
(like writing in register using complex rules).

With JPA:

• आप बस Java class ke objects create karo, aur system automatically usse register (DB)
mein sahi तरीके se handle kar leta hai.

Q.11 What is the difference between stateful and stateless session beans?

Ans: Java EE (Jakarta EE) में िब हम Enterprise Java Beans (EJB) की बात करते हैं, तो दो
important types होते हैं:
Stateful Session Bean
Stateless Session Bean

1. Stateful Session Bean kya hota hai?

Stateful Session Bean ek aisa bean hota hai jo client ke saath apna state
(data/memory) maintain karta hai.
मतलब: Agar ek client ne kuch data store kiya, to wahi data usi client ke liye alag se
maintain hoga.

Features:

• Ek client ke liye ek dedicated instance.


• Client-specific data store kar sakte ho.
• Jab tak session active hai, data yaad rahega.
• User logout kare ya session expire ho to state destroy ho jata hai.

Real-Life Example:

मान लो तुम Amazon पर shopping कर रहे हो, और तुमने cart में items डाले। Cart tumhara
personal hai, kisi aur customer ka cart alag hoga।
इस case में Stateful Session Bean की तरह cart data specific client ke liye state maintain
करता है ।

2. Stateless Session Bean kya hota hai?

Stateless Session Bean client ke saath koi state maintain nahi karta.
Har baar client request kare, to naye fresh context mein request process hoti hai.

Features:

• No client-specific data.
• Beans ko baar-baar reuse kiya ja sakta hai (pooled).
• Fast & efficient.
• Scalable in large applications.

Real-Life Example:

मान लो tumne ek ATM machine se balance check kiya। Har customer ke liye machine same
kaam karegi — koi personal data yaad nahi rakhegi।
याकन, हर transaction independent होता है = Stateless Session Bean.

Comparison Table: Stateful vs Stateless


Feature Stateful Session Bean Stateless Session Bean
State Maintain Yes, per client No
Client-Specific
Yes No
Data
Reusability Less (one per client) Yes (pooled & reused)
Performance Medium High
Shopping cart, online forms, login Login verification, currency
Best Use Case
session converter, etc.

@Stateful

public class ShoppingCartBean {

private List<String> cart = new ArrayList<>();

public void addItem(String item) {

[Link](item);

public List<String> getCart() {

return cart;

Har client ke liye alag cart banega.

Stateless Example:

@Stateless

public class CalculatorBean {

public int add(int a, int b) {

return a + b;
}

(Multithreading:)
Q.1 What is a thread and what are the different stages in its
lifecycle?

Ans: What is a Thread?


➤ Thread ek lightweight sub-process होता है , जो independently execute हो सकता है , लेककन
main program के अोंदर ही चलता है ।

➤ Java में एक Thread एक class होती है ([Link]), जो एक task को background में या


साथ में perform कर सकता है — कजससे हमारा application fast और responsive बनता है ।

Real-life Example:

सोचो तुम एक मोबाइल चला रहे हो:

• एक तरर् तुम YouTube पर वीबडयो दे ख रहे हो,


• दू सरी तरर् WhatsApp पर message आ रहे हैं ,
• और साथ ही file download हो रही है ।

हर activity को हम एक thread मान सकते हैं — ये सारे काम एक ही मोिाइल (main process) में
हो रहे हैं लेककन अलग-अलग threads के ज़ररए।

Thread Lifecycle (Stages)

Java में एक Thread के 5 main states होते हैं :

1. New

2. Runnable

3. Running

4. Blocked/Waiting

5. Terminated
1. New (Created State)

जब हम एक Thread object create करते हैं , लेककन उसे start() नहीों ककया गया होता।

Thread t = new Thread(); // New state

Real-life Analogy: तुमने ककसी को नौकरी पे रखा है लेककन अभी काम चालू नहीों ककया।

2. Runnable (Ready to Run)

जब हम start() method call करते हैं , तो Thread Runnable state में चला जाता है । अब ये CPU से
चलने का इों तज़ार कर रहा है ।

[Link](); // Now in Runnable state

Real-life Analogy: Employee office में आ गया है और manager के बोलने का इों तज़ार कर
रहा है कक "अब काम चालू करो।"

3. Running

जब Thread को CPU allocate होता है और वो actual में execute होता है — तब वो Running state में
होता है ।

Real-life Analogy: Manager ने कह कदया — "अब काम िुरू करो" — और employee काम
करने लग गया।

4. Blocked / Waiting / Timed Waiting

Thread temporarily pause हो जाता है — या तो ककसी resource का इों तज़ार कर रहा है , या कोई
और Thread काम कर रहा है उसी चीज़ पर।

[Link](1000); // Timed Waiting

Types:

• Waiting: कबना टाइम कलकमट के pause (e.g., join())


• Timed Waiting: कुछ समय के कलए pause (e.g., sleep(), wait(time))
• Blocked: Resource ककसी और thread के पास है

Real-life Analogy: Employee ककसी file के कलए इों तज़ार कर रहा है जो ककसी और के पास है ।
5. Terminated (Dead)

Thread का काम पूरा हो गया या कोई exception आ गया, तो वो Dead हो जाता है ।

Real-life Analogy: Employee ने अपना काम ख़त्म कर कलया या job छोड़ दी।

Thread Lifecycle Diagram :

Example in Code:

class MyThread extends Thread {

public void run() {

[Link]("Thread is running...");

public class Main {

public static void main(String[] args) {

MyThread t = new MyThread(); // New state

[Link](); // Runnable → Running


}

Extra: Thread को िनाने के दो तरीके होते हैं:

1. Thread class को extend करना

2. Runnable interface को implement करना

Q.2 What is the difference between process and thread?


Ans: Java में Process और Thread दोनोों ही program execution से जुड़ी हुई concepts हैं, लेककन
ये अलग-अलग काम करते हैं और अलग-अलग तरीके से behave करते हैं ।

1. Process kya hota hai?

Definition:

• Ek process ek independent program hota hai jo OS (Operating System) ke andar


chal raha hota hai.
• Har process ka apna memory space hota hai, aur ek process dusre process ke memory
ko directly access nahi kar sakta.

Example:

Agar tum Chrome, Spotify, aur VS Code teen alag apps open karte ho, toh ye tino alag-alag
processes ke रूप में run हो रही होती हैं ।

2. Thread kya hota hai?

Definition:

• Ek thread ek lightweight sub-unit hota hai process ka.


• Ek process ke andar multiple threads ho sakte hain jo same memory share karte
hain.
• Thread ka use parallel/efficient execution ke कलए hota hai.

Example:

Agar tum Chrome mein ek tab video चला रहे हो, दू सरे tab में download और तीसरे में webpage
scroll कर रहे हो — ये सारे काम ek hi Chrome process ke different threads se हो रहे हैं ।
Java Example Code:

Process Example (via [Link]().exec()):

public class ProcessExample {

public static void main(String[] args) {

try {

// Notepad ko launch karna ek naye process ke roop mein

Process process = [Link]().exec("[Link]");

} catch (Exception e) {

[Link]();

Yahaan Notepad ek naya process ke roop mein launch ho raha hai.

Thread Example (via extending Thread):

class MyThread extends Thread {

public void run() {

[Link]("Thread " + [Link]().getId() + " is running");

public class ThreadExample {

public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();


[Link](); // Thread 1

[Link](); // Thread 2

Yahaan ek hi Java program ke andar do threads parallel run kar rahe hain।

Real-Life Analogy:

Process:

Ek restaurant ka kitchen — har kitchen ek alag process hai।

Threads:

Kitchen ke andar alag chefs (threads) – ek roti bana raha hai, ek sabzi, ek salad – sab same
kitchen (memory space) mein kaam कर रहे हैं ।

Q.3 What are the different types of thread priorities available


in Java?

Ans: Java में threads को priorities दी जा सकती हैं ताकक JVM यह तय कर सके कक कौन से
thread को पहले execute करना है ।
Priority का मतलब है – importance level of thread in execution scheduling.

Thread Priority in Java:

Java में thread की priority एक integer (1 से 10) के बीच होती है :

Constant Value Description


Thread.MIN_PRIORITY 1 Lowest priority (सबसे कम)
Thread.NORM_PRIORITY 5 Default priority (मध्यम/normal)
Thread.MAX_PRIORITY 10 Highest priority (सबसे ज्यादा)

Default priority = 5 (जब आप खुद set नहीों करते)


Thread Priority कैसे set करते हैं?

Thread t = new Thread();

[Link](7); // Priority between 1 to 10

How JVM uses Priority (Important Note):

• Thread priority execution पर depend नही ीं करती — यह कसर्फ JVM को hint दे ती है ।


• कुछ OS (जैसे Windows) priority का respect करते हैं , लेककन कुछ OS में यह ignore भी हो
सकता है ।

Real-Life Example:

मान लीकजए आपके पास 3 काम करने वाले लोग हैं :

1. Cleaner → कम जरूरी काम


2. Clerk → Medium जरूरी काम
3. Boss → सबसे जरूरी काम

अगर सभी को एक ही समय पर काम कदया जाए — तो आप चाहोगे कक Boss का काम पहले हो, कर्र
Clerk, कर्र Cleaner.

Java threads भी वैसा ही behave करते हैं ।

Code Example:

class MyThread extends Thread {

public void run() {

[Link]("Running thread: " + [Link]().getName()

+ " with priority: " + [Link]().getPriority());

public class ThreadPriorityDemo {

public static void main(String[] args) {


MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

MyThread t3 = new MyThread();

[Link](Thread.MIN_PRIORITY); // 1

[Link](Thread.NORM_PRIORITY); // 5 (default)

[Link](Thread.MAX_PRIORITY); // 10

[Link]("Cleaner");

[Link]("Clerk");

[Link]("Boss");

[Link]();

[Link]();

[Link]();

Possible Output:

Running thread: Boss with priority: 10

Running thread: Clerk with priority: 5

Running thread: Cleaner with priority: 1

⚠ Note: कभी-कभी output unordered हो सकता है क्ोोंकक JVM/OS scheduling depend करता
है ।

Q.4 What is context switching in Java?

Ans: Definition:
Context Switching ka matlab hota hai:

Jab CPU ek thread ka kaam chhod kar dusre thread ka kaam karna start karta
hai, to beech mein jo state save/restore hoti hai — usi process ko context
switching kehte hain.

Ye concept multithreading mein aata hai.

Java mein Threads aur Context Switching:

Java mein jab hum multiple threads run karte hain, to CPU unmein se kisi ek ko ek
time par execute karta hai (even if humne multiple start kiye hain).

Context Switching tab hoti hai jab:

• Ek thread complete nahi hua hota, phir bhi CPU dusre thread pe switch karta
hai.
• Java’s Thread Scheduler decide karta hai ki kis thread ko CPU milega.

Context Switching ke steps:

1. Current thread ka state (registers, variables, program counter) save hota


hai.
2. New thread ka previously saved state wapas load hota hai.
3. CPU naye thread pe kaam karna start karta hai.

Note:

• Context switching ka time CPU time consume karta hai.


• Zyada context switching se performance degrade ho sakta hai (jise hum
thread overhead kehte hain).

Real-Life Example:

Example 1: Classroom Analogy


• Socho ek teacher (CPU) hai jo 3 students (threads) ko alag-alag question solve
karne ko bolta hai.
• Ek student solve kar hi raha hota hai, tabhi teacher bolta hai — "अब तुम रुको,
दू सरे student से पूछते हैं ।"
• Fir third student ke paas jaata hai.

Jab bhi teacher ek student se dusre pe switch karta hai, usko yaad rakhna padta
hai ki pehle student kaha tak pahucha tha — yahi hai context switching.

Java Code Example (Multithreading):

class MyThread extends Thread {

public void run() {

for (int i = 1; i <= 3; i++) {

[Link]([Link]().getName() + " - Step " + i);

public class ContextSwitchingExample {

public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

[Link]("Thread-1");

[Link]("Thread-2");

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

Output (may vary):

Thread-1 - Step 1

Thread-2 - Step 1

Thread-1 - Step 2

Thread-2 - Step 2

Thread-1 - Step 3

Thread-2 - Step 3

Yahaan CPU kabhi Thread-1 run karta hai, kabhi Thread-2 — yahi switching context
switching ke zariye possible hoti hai.

Q.5 What is the difference between user threads and Daemon


threads?

Ans: Java में threads दो प्रकार के होते हैं:


User Threads
Daemon Threads

दोनोों का काम background में task perform करना होता है , लेककन इनके behavior में कुछ
important र्कफ होता है ।

1. User Thread क्ा है?

• ये main या foreground thread होते हैं।


• जब तक user thread चल रहा है , JVM को process को alive रखना पड़ता है ।
• यह normal thread होता है जो main task को perform करता है ।

Example:
public class UserThreadExample {

public static void main(String[] args) {

Thread t = new Thread(() -> {

[Link]("User thread is running...");

});

[Link]();

यह एक normal user thread है ।

2. Daemon Thread क्ा है?

• यह background service thread होता है ।


• Daemon thread का purpose होता है ककसी user thread की help करना, जैसे:
o Garbage Collection
o Finalizer
o Timer task
• जब सारे user threads खत्म हो जाते हैं , तब JVM daemon threads को खुद िींद कर
दे ता है।

Example:

public class DaemonThreadExample {

public static void main(String[] args) {

Thread t = new Thread(() -> {

while (true) {

[Link]("Daemon thread is running...");

try { [Link](1000); } catch (Exception e) {}


}

});

[Link](true); // इसे daemon बना कदया गया

[Link]();

[Link]("Main thread ends...");

}}

Output:

Daemon thread is running...

Main thread ends...

उसके बाद daemon thread भी बोंद हो जाता है automatically.

Real-Life Example:

User Thread:

मान लो आप Word में कोई document type कर रहे हो — आपका typing task User Thread
है ।

Daemon Thread:

अब Word खुद background में auto-save करता है — यह काम Daemon Thread करता है ।

अगर आप typing बोंद कर दो (User Thread खत्म हो गया), तो auto-save (Daemon Thread)
भी अपने आप बोंद हो जाएगा।

Important Notes:

1. Daemon thread को start करने से पहले set करना होता है :

[Link](true);

2. Once thread is started, setDaemon() नहीों चला सकते —


IllegalThreadStateException आ जाएगी।
3. Main thread भी user thread होता है, और जब सभी user threads खत्म होते हैं , तो
daemon threads भी terminate हो जाते हैं ।
Q.6 What is synchronization?

Ans: Java में Synchronization एक ऐसी technique है जो multi-threaded environment


में data consistency और thread safety को maintain करने के कलए use होती है ।

What is Synchronization in Java?

Synchronization ka matlab hai:

"Ek time pe sirf ek thread critical section (shared resource) ko access kar sake."

Java में जब एक से ज़्यादा threads ककसी एक ही object/resource को access करते हैं और


उसपर read/write operations करते हैं , तो chances हैं कक data corrupt हो जाए।

इसकलए Java में हम synchronized keyword use करते हैं ताकक ek waqt pe ek hi thread
shared resource pe kaam kare.

Real-Life Example:

Example: Restaurant Order Counter

मान लो एक restaurant का single order counter है ।


बहुत सारे waiters हैं (threads), लेककन counter पर एक समय में बसफफ एक ही waiter order
ले सकता है।

अगर सब waiter एक साथ counter पर आ जाएों , तो confusion, galat order, aur data mix-up
ho सकता है ।

इसकलए ek system hona chahiye jo ensure kare ki:

• Ek samay pe ek hi waiter counter pe aaye.


• Dusra waiter tab tak wait kare jab tak pehla waiter ka kaam complete na ho.

यही काम synchronized keyword करता है Java में।

Java Code Example (Without Synchronization)

class Counter {

int count = 0;
void increment() {

count++; // not synchronized

public class Test {

public static void main(String[] args) {

Counter c = new Counter();

Thread t1 = new Thread(() -> {

for (int i = 0; i < 1000; i++) [Link]();

});

Thread t2 = new Thread(() -> {

for (int i = 0; i < 1000; i++) [Link]();

});

[Link]();

[Link]();

try {

[Link]();

[Link]();
} catch (Exception e) {}

[Link]("Final count: " + [Link]); // May not be 2000

Output:

Final count: 1875 // wrong output (random each time)

Java Code Example (With Synchronization)

class Counter {

int count = 0;

synchronized void increment() {

count++; // synchronized

public class Test {

public static void main(String[] args) {

Counter c = new Counter();

Thread t1 = new Thread(() -> {

for (int i = 0; i < 1000; i++) [Link]();

});
Thread t2 = new Thread(() -> {

for (int i = 0; i < 1000; i++) [Link]();

});

[Link]();

[Link]();

try {

[Link]();

[Link]();

} catch (Exception e) {}

[Link]("Final count: " + [Link]); // Always 2000

Output:

Final count: 2000 // Correct

Types of Synchronization in Java

Type Description
Method Synchronization Entire method lock with synchronized keyword.
Block Synchronization Lock only a specific block of code inside a method.
Static Synchronization Synchronize static methods (class-level lock).
Q.7 What is a deadlock in Java?

Ans: Definition (Hinglish):

Java में Deadlock एक ऐसी ल्िकत होती है जहााँ दो (या ज़्यादा) threads एक-दू सरे का
resource ले कर फँस जाते हैं और कोई भी आगे execute नहीों कर पाता।

Simple Words में: 2 threads एक-दू सरे की चीज़ पकड़ कर wait करते रहते हैं , और कोई भी
resource छोड़ता नहीों — दोनोों रुक जाते हैं = Deadlock

Real-Life Example:

मान लो:

• लड़का A के पास चम्मच है और उसे काींटे (fork) चाकहए खाना खाने के कलए।
• लड़का B के पास काींटे (fork) है और उसे चम्मच चाकहए।

अब दोनोों एक-दू सरे की चीज़ का wait कर रहे हैं — लेककन कोई भी अपनी चीज़ छोड़ता नहीों।
दोनोीं फँस गए — ये Deadlock है।

Java Example: Deadlock with Threads

class Resource {

void printMessage(String msg) {

[Link](msg);

public class DeadlockExample {

public static void main(String[] args) {

final Resource resource1 = new Resource(); // like Spoon


final Resource resource2 = new Resource(); // like Fork

// Thread 1 trying to lock resource1 then resource2

Thread t1 = new Thread(() -> {

synchronized (resource1) {

[Link]("Thread 1 locked Resource 1");

// sleep to simulate delay

try { [Link](100); } catch (Exception e) {}

synchronized (resource2) {

[Link]("Thread 1 locked Resource 2");

});

// Thread 2 trying to lock resource2 then resource1

Thread t2 = new Thread(() -> {

synchronized (resource2) {

[Link]("Thread 2 locked Resource 2");

// sleep to simulate delay

try { [Link](100); } catch (Exception e) {}


synchronized (resource1) {

[Link]("Thread 2 locked Resource 1");

});

[Link]();

[Link]();

Output:

• Thread 1 locks Resource 1


• Thread 2 locks Resource 2
दोनोों एक-दू सरे के resource का इों तज़ार करते रहते हैं — और program hang हो
जाता है = Deadlock

Deadlock की Conditions:

Deadlock होने के कलए ये चारोों conditions satisfy होनी चाकहए:

1. Mutual Exclusion – एक resource को एक time पर एक ही thread use कर सकता है ।


2. Hold and Wait – Thread एक resource पकड़े हुए दू सरे का wait कर रहा है ।
3. No Preemption – Resource जब तक voluntarily release न हो, कोई छीन नहीों
सकता।
4. Circular Wait – एक cycle बनती है जहााँ हर thread दू सरे का resource hold ककए है।

Deadlock को कैसे Avoid करें ?

1. Resource ordering maintain करें – सभी threads हमेिा एक ही order में lock करें ।
2. Try-Lock mechanism use करें (Java 5+ ReentrantLock के साथ)।
3. Timeout रखें locks में – अगर time exceed हो जाए तो छोड़ दें ।

ReentrantLock lock1 = new ReentrantLock();

if ([Link](1000, [Link])) {

try {

// do work

} finally {

[Link]();

}}

Q.8 What is the use of the wait() and notify() methods?

Ans: Java में wait() और notify() methods का उपयोग multithreading में ककया जाता है —
खासकर जब दो या दो से अकधक threads को एक shared resource पर synchronized तरीके
से काम करना होता है ।

wait() और notify() — क्ा करते हैं?

wait()

• एक thread को pause (रोक) दे ता है — जब तक कक कोई दू सरा thread उसे notify नहीों


करता।
• ये method Object class से आता है ।
• यह method बसफफ synchronized block/method के अोंदर ही call ककया जा सकता है ।

notify()

• एक thread को जो wait() पर रुका है , वापस शुरू करता है ।


• अगर multiple threads wait() पर हैं , तो एक को randomly notify करे गा।

Real-Life Analogy: "Customer और Shopkeeper"

Imagine करो:

• Customer आता है दु कान पर और कहता है : "Milk दो!"


• लेककन Shopkeeper कहता है : "Abhi milk नहीों है , wait karo."
• Customer बैठकर wait करता है (→ wait() method).
• थोड़ी दे र में Milk आता है , तो Shopkeeper बोलता है : "Milk आ गया, ले लो" (→ notify()
method).
• अब Customer कर्र से active होता है और milk लेता है ।

Java Code Example:

class MilkShop {

boolean milkAvailable = false;

synchronized void buyMilk() throws InterruptedException {

[Link]("Customer: Milk hai kya?");

while (!milkAvailable) {

[Link]("Shopkeeper: Nahi hai, wait karo...");

wait(); // Customer waits

[Link]("Customer: Yay! Milk mil gaya!");

milkAvailable = false;

synchronized void restockMilk() {

[Link]("Shopkeeper: Milk aa gaya hai.");

milkAvailable = true;

notify(); // Notify the waiting customer

}
}

public class WaitNotifyExample {

public static void main(String[] args) {

MilkShop shop = new MilkShop();

// Customer Thread

Thread customer = new Thread(() -> {

try {

[Link]();

} catch (InterruptedException e) {

[Link]();

});

// Shopkeeper Thread

Thread shopkeeper = new Thread(() -> {

try {

[Link](3000); // Simulate delay in restocking

[Link]();

} catch (InterruptedException e) {

[Link]();

});
[Link]();

[Link]();

Output:

Customer: Milk hai kya?

Shopkeeper: Nahi hai, wait karo...

Shopkeeper: Milk aa gaya hai.

Customer: Yay! Milk mil gaya!

Important Notes:

• wait(), notify() → केवल synchronized block/method के अोंदर काम करते हैं।


• wait() method को call करने पर InterruptedException handle करना जरूरी होता है ।
• notifyAll() → सभी waiting threads को notify करता है ।

Q.9 What is the difference between synchronized and volatile


in Java?

Ans: Java में synchronized और volatile दोनोों का उपयोग multi-threading में ककया जाता है
— लेककन इन दोनोों का उद्दे श्य (purpose) और काम करने का तरीका अलग होता है ।

1. volatile keyword kya karta hai?

Purpose:

• Jab ek variable volatile declare kiya jata hai, to uski value directly main
memory se read/write hoti hai, na ki thread-local cache se.

Problem it solves:
Multiple threads agar ek variable access kar rahe hain, to kabhi-kabhi ek thread
dusre thread ke changes ko dekhta hi nahi hai, because wo uska local copy use kar
raha hota hai.

volatile ensure karta hai ki sabhi threads always latest value padhein — main
memory se.

Example (Real-Life Analogy):

class Example {

volatile boolean flag = false;

public void writerThread() {

flag = true; // This change goes directly to main memory

public void readerThread() {

while (!flag) {

// waiting until flag becomes true

[Link]("Flag is true, continuing...");

Without volatile, readerThread shayad kabhi flag == true dekhe hi na.


With volatile, readerThread ko latest true value dikhegi.

Real-Life Analogy:
सोचो कक दो लोग एक whiteboard पर काम कर रहे हैं । एक कलखता है (writer), दू सरा पढ़ता है
(reader)।

• अगर writer एक board पर कलखता है , और reader दू सरा board दे खता है (local copy),
तो उसको update नहीों कदखेगा।
• volatile का मतलब — दोनोों को बसफफ एक ही common board कदखे।

2. synchronized keyword kya karta hai?

Purpose:

• synchronized thread safety provide karta hai — मतलब ek time par sirf ek
thread hi block ke andar ka code access kar sakta hai.
• Isse race condition avoid hoti hai.

Example:

class Counter {

int count = 0;

public synchronized void increment() {

count++;

Agar multiple threads increment() method ko call karein, to synchronized ensure


karega ki ek thread finish kare tabhi doosra enter kare.

Real-Life Analogy:

सोचो कक एक बाथरूम है कजसपर ताला है । कसर्फ एक व्यल्ि ही एक समय में अोंदर जा सकता है ।

• synchronized = वो ताला
• Method/block = बाथरूम
जि volatile काम नही ीं करे गा?

class Counter {

volatile int count = 0;

public void increment() {

count++; // NOT ATOMIC!

यहाों volatile होने के बावजूद count++ thread-safe नहीों है , क्ोोंकक यह एक atomic


operation नहीों है (3 steps — read, modify, write)।

इसके कलए synchronized चाकहए:

public synchronized void increment() {

count++;

Conclusion ( कब क्ा Use करें ? )

Situation Use
Agar sirf ek simple variable ko latest value ke liye access karna hai volatile
Agar kisi critical section me multiple threads ka access control karna
synchronized
hai
Agar atomic operations chahiye (e.g. count++) synchronized

Q.10 What is the purpose of the sleep() method in Java?

Ans: Java में sleep() method का purpose current thread को temporarily रोकना
(pause करना) होता है — यानी कक वह कुछ समय के कलए काम करना बोंद कर दे गा और
specified milliseconds तक "सो जाएगा"।
Method Signature:

[Link](milliseconds); // OR

[Link](milliseconds, nanoseconds);

• यह method Thread class का static method है ।


• ये method एक checked exception (InterruptedException) throw करता है , इसकलए
इसे try-catch block में wrap करना होता है ।

Purpose of sleep() Method:

1. Thread को कुछ समय के बलए रोकना — जैसे animation या background task के


बीच delay दे ना।
2. CPU resources िचाने के बलए — जब कोई thread को तुरोंत कुछ करने की ज़रूरत नहीों
होती।
3. Simulation या Timer-based काम के बलए — जैसे countdown, wait time, delay,
आकद।
4. Testing purpose के बलए — async code के delay को simulate करने के कलए।

Real Life Example (Hinglish Explanation):

मान लो तुमने एक program कलखा है जो हर 1 सेकोंड बाद ककसी मिीन की temperature value
को print करता है । तुम्हें चाकहए कक हर reading के बीच थोड़ा pause हो — यहााँ sleep() काम
आता है ।

Example Code:

public class SleepExample {

public static void main(String[] args) {

[Link]("Machine temperature readings:");

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

[Link]("Reading " + i + ": " + (20 + i) + "°C");


try {

[Link](1000); // 1 second pause

} catch (InterruptedException e) {

[Link]("Thread interrupted!");

}}

[Link]("All readings done.");

Output:

Machine temperature readings:

Reading 1: 21°C

(wait 1 second)

Reading 2: 22°C

(wait 1 second)

...

Reading 5: 25°C

All readings done.

Use Cases:

• Countdown timer
• Delayed loading
• Retry logic (like: wait for 5 seconds and try again)
• Animation pauses
• Sensor or data logging delays
Q.11 What is the difference between wait() and sleep() in
Java?

Ans: Java में wait() और sleep() दोनोों methods को अक्सर multi-threading में use ककया
जाता है , लेककन दोनोों का behavior, purpose और scope पूरी तरह से अलग होता है ।

1. Definition और Purpose

sleep() method:

• Belongs to: Thread class


• Purpose: Thread को temporarily रोकना (pause करना) for a specific time (in
milliseconds).
• ये कसर्फ time-based pause है ।

wait() method:

• Belongs to: Object class


• Purpose: Current thread को tab tak wait karna jab tak kisi aur thread ne us
object par notify() ya notifyAll() nahi bulaya ho.
• ये thread communication ke liye use होता है — synchronization context में।

2. Use Case

Feature sleep() wait()


Delay or pause Thread communication
Used for
thread (coordination)
Belongs to Thread class Object class
Requires synchronized
Nahi Haan (mandatory)
block?
Wakes up automatically? After time expires Jab tak notify() nahi aata
Throws Exception InterruptedException InterruptedException

Real-life Analogy

sleep():
मान लो एक आदमी सुबह उठकर कहता है : "मैं 5 कमनट के कलए सोने जा रहा हाँ " — तो वो खुद से 5
बमनट िाद उठे गा।

wait():

वही आदमी कहता है : "मैं तब तक नहीों उठूोंगा जब तक कोई मुझे जगा ना दे " — याकन उसे कोई और
notify करे गा, तब ही वो उठे गा।

Code Example

sleep() Example:

public class SleepExample {

public static void main(String[] args) {

[Link]("Sleeping for 3 seconds...");

try {

[Link](3000); // 3 seconds

} catch (InterruptedException e) {

[Link]();

[Link]("Awake now!");

Output:

Sleeping for 3 seconds...

(waits 3 sec)

Awake now!
wait() Example:

class WaitExample {

public static void main(String[] args) {

final Object lock = new Object();

Thread t1 = new Thread(() -> {

synchronized(lock) {

[Link]("Thread 1 waiting...");

try {

[Link](); // waits until notified

} catch (InterruptedException e) {

[Link]();

[Link]("Thread 1 resumed.");

});

Thread t2 = new Thread(() -> {

synchronized(lock) {

[Link]("Thread 2 notifying...");

[Link](); // wakes up thread 1

});
[Link]();

try { [Link](1000); } catch (Exception e) {}

[Link]();

Output:

Thread 1 waiting...

(wait 1 sec)

Thread 2 notifying...

Thread 1 resumed.

Q.12 What is the difference between notify() and notifyAll() in Java?

Ans: Java में notify() और notifyAll() दोनोों ही methods Object class का कहस्सा हैं और
multithreading में inter-thread communication के कलए इस्तेमाल होते हैं — खासकर जब
हम wait() method के साथ synchronization का इस्तेमाल करते हैं ।

Basic Concept:

जब एक thread shared resource के कलए wait() करता है , तो वह waiting state में चला जाता
है और तब तक नहीों चलता जब तक कोई दू सरा thread उसे notify() या notifyAll() से signal न
दे ।

notify() kya karta hai?

• notify() केवल एक waiting thread को notify करता है (randomly चुने गए ककसी एक


को) कक वो दोबारा run कर सकता है ।

Example:

मान लो एक ATM में 3 लोग line में हैं । Teller कसर्फ एक को कहता है :
“अींदर आओ!”
बाकी दो लोग इों तजार करते हैं।
notifyAll() kya karta hai?

• notifyAll() सभी waiting threads को notify करता है कक वे resource के कलए दोबारा


competition करें ।

Example:

वही ATM वाला case — Teller कहता है :


“सभी लोग अींदर आ जाओ, जो पहले आओ वो पहले सेवा लो!”
सारे threads जाग जाते हैं और synchronization के कहसाब से race करते हैं ।

Imagine karo:

एक washroom है जो lock होता है , और कई लोग बाहर खड़े हैं।

notify():

Watchman कसर्फ एक को बोलता है "जा सकता है ।" बाकी लोग wait करते हैं।

notifyAll():

Watchman सभी को बोलता है "अब जा सकते हो" — अब जो जल्दी पहुों च गया वही washroom
use करे गा।

Java Code Example:

class SharedResource {

synchronized void waitingThread() {

try {

[Link]([Link]().getName() + " is waiting...");

wait();

[Link]([Link]().getName() + " is notified and


resumed.");

} catch (InterruptedException e) {

[Link]();

}
synchronized void notifyOne() {

notify(); // Only one waiting thread will be notified

synchronized void notifyEveryone() {

notifyAll(); // All waiting threads will be notified

public class NotifyVsNotifyAllExample {

public static void main(String[] args) throws InterruptedException {

SharedResource resource = new SharedResource();

Runnable waitingTask = () -> [Link]();

Thread t1 = new Thread(waitingTask, "Thread-1");

Thread t2 = new Thread(waitingTask, "Thread-2");

Thread t3 = new Thread(waitingTask, "Thread-3");

[Link]();

[Link]();

[Link]();
[Link](2000); // थोड़ी दे र बाद notifier call करे गा

// [Link](); // Try this to notify one

[Link](); // Try this to notify all

Summary:

Point notify() notifyAll()


केवल एक thread को उठाता है
सभी threads को उठाता है
तेज़ काम करता है (less overhead)
Deadlock का chance अगर गलत इस्तेमाल हो
Use करो जब only one thread से काम हो जाए

You might also like