OOPS Concepts in Java Explained in Hinglish
OOPS Concepts in Java Explained in Hinglish
java
class Student {
int rollNo;
String name;
void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}
java
class Account {
private int balance;
// Setter
public void setBalance(int amt) {
balance = amt;
}
// Getter
public int getBalance() {
return balance;
fi
}
}
Yahan balance variable private hai, toh direct access allowed nahi hai. Set aur get
methods ke through access hota hai.
3. Inheritance
Inheritance ki help se ek class doosri class ki properties aur methods inherit kar
sakti hai. Isse code reuse hota hai aur naye features add kiye ja sakte hain.
java
class Parent {
void display() {
[Link]("Parent class");
}
}
class Child extends Parent {
void show() {
[Link]("Child class");
}
}
Yahan 'Child' class ne 'Parent' ki functionality inherit ki hai.
4. Polymorphism
Polymorphism ka matlab ek hi action ko alag-alag tareeke se perform karna. Jaise
method overloading aur overriding.
java
class Animal {
void sound() {
[Link]("Animal sound");
}
}
java
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
[Link]("Draw Circle");
}
}
'Shape' class abstract hai, jismein abstract method draw() hai, har child class apni
style se implement karegi.
Checked Exception
Checked exceptions wo hote hain jo compile time par check kiye jaate hain. Java
compiler aapko force karta hai ki aap inko handle karo (try-catch ya throws) kyunki
yeh mostly external resources par depend karte hain jaise les, network, database,
etc.
Example:
java
import [Link].*;
Unchecked Exception
Unchecked exceptions runtime par aate hain, matlab inko compile time par check
nahi kiya jaata. Yeh zyada tar programming mistakes ki wajah se aate hain—for
example, divide by zero, array index galat, null object par method call, etc.
Example:
java
public class UncheckedDemo {
public static void main(String[] args) {
int a = 10;
fi
fi
int b = 0;
int c = a / b; // ArithmeticException runtime par throw hoga
[Link](c);
}
}
Yahan ArithmeticException ek unchecked exception hai, isko handle karna
zaroori nahi hai, compiler warning nahi dega, lekin program crash ho jayega agar
exception aaya.
Di erence Table
Feature Checked Unchecked
Exception Exception
Compile time Check karte Check nahi
par hain karte hain
Parent class [Link] [Link]
ption meException/
Error
Handle karna Zaroori hai (try- Optional (agar
catch/throws) chahe toh
handle karo)
Example FileNotFoundE NullPointerExc
xception, eption,
IOException ArithmeticExce
ption,
ArrayIndexOut
OfBoundsExce
ption
Q3) what is super class of all the classes in java and explain all the method of
object class ?
Java mein sabhi classes ka super class Object class hota hai. Matlab, jitni bhi
classes aap banaate ho (chahe user-de ned, chahe system-de ned), sab inherit
karte hain Object class ko directly ya indirectly. Isliye Object class ki properties
aur uske methods sab classes mein milte hain.
Object Class ke Important Methods aur Hinglish Explanation
1. toString()
Is method se object ki String representation milti hai. Agar override nahi kiya hai
toh class name + hex code return hota hai. Commonly debugging mein useful hai.
java
class Student {
public String toString() {
ff
fi
fi
return "Student Object";
}
}
public class Demo {
public static void main(String[] args) {
Student s = new Student();
[Link](s); // Output: Student Object
}
}
Jab [Link](object); karte ho toh internally toString() call hota hai.
2. equals(Object obj)
Yeh method do objects ko compare karta hai. Agar values same hain, toh true
return karega. Default behaviour sirf reference compare karta hai (matlab dono ek
hi memory address pe hain ya nahi).
java
Student s1 = new Student();
Student s2 = s1;
[Link]([Link](s2)); // true
Override karke values ko bhi compare kar sakte hain.
3. hashCode()
Object ka ek unique integer hash code generate karta hai, jo collections
(HashMap, HashSet) me zaruri hota hai.
java
class Student {}
public class Demo {
public static void main(String[] args) {
Student s = new Student();
[Link]([Link]());
}
}
Hash code collections ke performance ke liye important hai.
4. getClass()
Object ki actual runtime class return karta hai. Code ke meta information nikalne
mein use hota hai.
java
Student s = new Student();
[Link]([Link]()); // Output: class Student
Isse aap pata kar sakte hain object kis class ka hai.
5. clone()
Isse object ka copy (clone) bana sakte ho. Use karne ke liye Cloneable interface
implement karna zaruri hai.
java
class Student implements Cloneable {
int roll;
public Object clone() throws CloneNotSupportedException {
return [Link]();
}
}
Mostly advanced use cases mein hota hai.
6. nalize()
Jab object destroy hone wala hai (garbage collection hone par), tab yeh method
call hota hai. Resource cleanup mein help karta hai.
java
protected void nalize() {
[Link]("Object is destroyed");
}
Iska use ab kam hota hai; recommended nahi hai modern Java mein.
7. wait(), notify(), notifyAll()
Multithreading mein synchronization ke liye use hote hain. Thread ko wait karwana,
wake karna, ya sabko wake karna possible hai.
java
// Sample with synchronized block and wait/notify
synchronized(obj) {
[Link]();
}
Concurrency handle karne ke liye use hota hai.
Java mein exception handling ke liye throw aur throws keywords use hote hain,
lekin dono ka role alag hota hai. Hinglish mein sab detail, di erentiation, aur code
ke saath samjha jaata hai.
throw Keyword
• Iska use manually exception ko throw karne ke liye hota hai (matlab khud
se exception uthana).
• Ye kisi bhi block ya method ke andar likha jaata hai.
• Syntax: throw new ExceptionType("message");
• Sirf ek hi exception ek baar throw kiya ja sakta hai.
Example Hinglish:
java
public class ThrowDemo {
public static void main(String[] args) {
int age = 15;
if(age < 18) {
throw new ArithmeticException("Access denied - Age kam hai");
}
[Link]("Access granted");
}
}
Yahan programmer khud se arithmetic exception throw kar raha hai jab age < 18
ho jaaye.
throws Keyword
fi
fi
ff
fi
fi
ff
• Iska use method signature mein hota hai, batane ke liye ki is method se
kaun-kaun si exception bahar ja sakti hai (pass ho sakti hai).
• Checked exceptions ke liye zaroori hai taki compiler ko pata ho ki calling
code ko handle karna padega.
• Syntax: returnType methodName() throws ExceptionType1,
ExceptionType2 { ... }
• Aap ek method ke signature mein multiple exception declare kar sakte
hain.
Example Hinglish:
java
import [Link].*;
Java mein String immutable isliye hota hai kyunki ek baar String object ban gaya,
uski value kabhi change nahi ho sakti—agar modify karne ki koshish karte ho toh
actually ek naya object banta hai, old value same hi rehti hai.
java
public class StringTest {
public static void main(String[] args) {
String str = "Bihar";
[Link](" Engineer");
[Link](str); // Output: Bihar
java
String s1 = "Java";
String s2 = "Java";
[Link](s1 == s2); // Output: true (pool ka same object)
Dono s1, s2 pool ke ek hi object ko refer karte hain, agar s1 ki value change hoti
toh pool ke sare references bhi change ho jaate, jo allowed nahi hai.
Immutability ki wajah se String fast, reliable aur secure banta hai—and ye Java
language design ka ek important principle hai.
Java mein == operator aur .equals() method dono comparison ke liye use hote
hain, lekin dono ka kaam bilkul alag hai. Hinglish mein isko detail, example aur
code ke saath explain kiya gaya hai.
ff
ff
fi
fi
ffi
1. == Operator
• == operator reference comparison karta hai—matlab do objects ka
memory address check karta hai, ki kya dono ek hi jagah ko point kar rahe hain.
• Primitive types (int, char, oat, etc.) ke liye == unki exact value compare
karta hai.
• Agar objects ka reference same hai (ek hi object), tab result true hoga,
warna false.
Example:
java
String s1 = "HELLO";
String s2 = "HELLO";
String s3 = new String("HELLO");
2. .equals() Method
• .equals() method value comparison karta hai—matlab do objects ki
actual content/value check karta hai, ki kya dono ka data same hai.
• By default (agar aap override nahi karte ho), Object class ki .equals() bhi
reference compare karti hai, lekin String class aur kuch dusri classes isko override
kar deti hain taaki actual value compare ho.
• Custom class mein generally aap override kar ke apni value compare kar
sakte hain.
Example:
java
String s1 = "HELLO";
String s2 = "HELLO";
String s3 = new String("HELLO");
Table Summary
Feature == Operator .equals() Meth
od
Comparison Reference Value/content
Type (memory (is data same?)
address)
fl
ff
Primitives Actual value Not applicable
(method nahi
hota)
Objects References Override karke
compare hota value/ elds
hai compare kar
sakte hain
Output s1 == s2 true/ [Link](s2) t
Example false rue/false
Override Nahin Haan, custom
Option logic add kar
sakte hain
Common Use Mostly Objects ka
primitives or actual data
string pool compare karna
Hinglish Key Points
• == operator sirf address check karta hai, value nahi. Java mein string
pool ki wajah se kabhi dono string ek hi address par bhi ho sakte hain, lekin mostly
nai object pe nahi hoga.
• .equals() method value/data compare karta hai, isliye kaa useful hai
object ki actual equality check karne ke liye.
• Agar aap apni custom class bana rahe ho, toh
generally .equals() override karna chahiye taki aap apni actual attribute compare
kar sako.
• Jab bhi string ya object ki actual value compare karni ho,
hamesha .equals() use karo, sirf reference compare karna ho toh == use karo.
Java mein JDK, JRE aur JVM teen important components hain, jinhe samajhna
zaruri hai agar aap Java development ya execution mein kaam karte ho. Hinglish
mein yeh sab detail mein, short points aur examples ke saath bataya gaya hai.
JVM (Java Virtual Machine) architecture ek complex system hai jo Java program ko
run karta hai. Hinglish mein, har ek part ka kaam simple language mein samjhaaya
gaya hai, taaki concepts bilkul clear ho.
Java mein Error aur Exception dono program ke ow ko disturb karte hain, lekin
dono bilkul alag situation ko represent karte hain. Hinglish mein, sab point,
di erence aur code ke saath samjhaaya gaya hai.
Error in Java
• Error wo problems hain jo system level pe aati hain—matlab JVM/
resource ke khatam hone, stack over ow, memory full, etc.
• Ye unrecoverable hote hain, inka solution nahi hota; program crash hi ho
jaata hai.
• Error mainly [Link] class ke objects hote hain, jaise
OutOfMemoryError, StackOver owError.
Code Example:
java
public class ErrorExample {
public static void main(String[] args) {
// StackOver owError example (in nite recursion)
print();
}
public static void print() {
print(); // yahan pe stack kabhi khatam nahi hoga, StackOver owError throw
ho jayega
ff
ff
fl
fl
fi
fl
fi
fi
fi
fl
fl
fi
}
}
Yahan pe program crash ho jaata hai, aap try-catch laga ke isko recover nahi kar
sakte.
Exception in Java
• Exception wo situations hain jo code mein aati hain—matlab input galat,
array index galat, le nahi mili, division by zero, etc.
• Exception recoverable hai, try-catch ke through handle kar sakte ho aur
program ko continue kara sakte ho.
• Exception mainly [Link] class ke objects hote hain; jaise
NullPointerException, FileNotFoundException.
Code Example:
java
public class ExceptionExample {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int c = a / b; // yahan ArithmeticException aayega
[Link](c);
} catch (ArithmeticException e) {
[Link]("Division by zero galat hai!");
}
[Link]("Rest of code runs...");
}
}
Yahan pe try-catch ke through exception recover ho gaya, program continue ho
gaya.
Summary Table
Feature Error Exception
Source System/ Coding/
Environment Program
problem mistakes
Example OutOfMemory NullPointerExc
Error, eption,
StackOver ow IOException
Error
Recoverable Nahi (mostly) Haan (try-
catch se)
Parent Class [Link] [Link]
ption
fl
fi
Handling Handle karna Handle karna
recommended zaroori hai
nahi
Type Always Checked &
unchecked Unchecked
Hinglish Key Points
• Error wo hai jo system level pe crash kar deta hai, recover nahi kar sakte,
code ka kaam nahi hai—jaise memory full, JVM down ho gaya.
• Exception wo hai jo aapke code ki galti se aata hai aur aap usko try-
catch se handle karke program ko safely run kara sakte ho.
• Exception ke liye handle karna zaroori hai, Error ke liye recommended
nahi hai (mostly program ko close kar dena chahiye).
• Dono throwable hain, par error hai system ka dikkat, exception hai
programmer ki dikkat.
Java mein nal, nally aur nalize() teeno alag-alag cheezein hain, although naam
milte-julte hain. Hinglish mein, har ek ka use, concept, aur code example ke saath
detail samjhaya gaya hai.
1. nal Keyword
• nal ek keyword hai, jo variable, method ya class ke saath use hota hai.
• Agar variable ko nal bana do, toh uski value r kabhi change nahi ho
sakti (constant ban jaata hai).
• Agar method ko nal bana do, toh subclass usko override nahi kar
sakta.
• Agar class ko nal bana do, toh usko inherit nahi kar sakte (koi child
class nahi ban sakti).
Code Example:
java
nal int x = 25; // x ab kabhi change nahi hoga
class Test {
nal void show() {
[Link]("Hello");
}
}
Agar nal variable, method ya class ko modify ya override karna try karoge toh
compile time pe error aa jayega.
fi
fi
fi
fi
fi
fi
fi
ff
fi
fi
fi
fi
fi
fi
fi
fi
fi
2. nally Block
• nally ek block hai, jo try-catch ke saath use hota hai.
• Chahe exception aaye ya nahi aaye, nally block hamesha execute hota
hai.
• Iska use resource cleanup, le close, connection close jaise operations
ke liye hota hai.
Code Example:
java
try {
int a = 10/0;
} catch (ArithmeticException e) {
[Link]("Exception aayi!");
} nally {
[Link]("Yeh block hamesha chalega");
}
Yahan pe chahe exception aaye ya nahi, nally block must execute hota hai.
3. nalize() Method
• nalize() ek method hai jo garbage collector object ko destroy karne se
pehle call karta hai.
• Iska use last moment resource cleanup ke liye hota hai—jaise database
close, le close, etc.
• Modern Java mein direct use recommended nahi hai; deprecated ho
chuka hai.
Code Example:
java
class Demo {
protected void nalize() {
[Link]("Finalize method called!");
}
}
public class Test {
public static void main(String[] args) {
Demo d = new Demo();
d = null;
[Link](); // Garbage Collector ko request
}
}
Jab Demo object destroy hone wala hai tab JVM nalize() call kar sakta hai.
Q11) what is thread and how many ways to create thread in java ?
Thread Ka Concept
• Jab aap koi Java program chalate ho, ek main thread automatically banta
hai (jo main() method run karta hai).
• Multithreading se aap ek saath multiple kaam kara sakte ho, jaise le
download, user input, aur data process — sab alag-alag threads mein.
java
// Thread class extend karke thread banana
class MyThread extends Thread {
public void run() {
[Link]("Thread chal raha hai!");
}
}
java
// Runnable interface implement karke thread banana
class MyRunnable implements Runnable {
public void run() {
[Link]("Thread bhi chal raha hai—Runnable waala!");
}
}
java
Thread t = new Thread(() -> [Link]("Lambda Thread!"));
[Link]();
Hinglish Tips
• Thread ka use: Parallel task karne ke liye (background task, UI
responsive rakhna, le download, etc.).
• Extends Thread: Use karo jab aapke class ko sirf ek hi parent class
chahiye ho.
• Implements Runnable: Zyada use hota hai, kyunki aap already kisi aur
class ko extend kar rahe ho to bhi thread bana sakte ho.
• Always start thread using .start(), not .run(), warna multithreading nahi
milegi
Q12) explain custom exception and how to create custom exception in java?
Java mein custom exception ka matlab hai apni khud ki exception class banana, jo
speci c problem ko handle kare – jab built-in exceptions se kaam nahi chale.
Hinglish mein, yeh bahut hi useful hai jab aap apne application ke special error
conditions ko clear aur readable tarike se handle karna chahte hain.
java
// Khud ki exception class bana rahe hain
class AgeException extends Exception {
public AgeException(String message) {
fi
fi
fi
fi
fi
fi
super(message); // Parent Exception class ka constructor call
}
}
Yahan AgeException ek custom exception hai jo message accept karti hai.
2. Exception Throw Karna
java
public class TestCustomEx {
public static void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age should be >= 18");
} else {
[Link]("Valid age: " + age);
}
}
Java mein serialization ka matlab hai kisi object ki complete state (matlab uske
variables ki value, class info, etc.) ko ek byte stream (binary format) mein convert
karna, taki usko le mein ya kisi network par bheja ja sake ya baad mein rse
waapas object mein convert kiya ja sake. Jab byte stream ko rse object banaate
hain, use deserialization kehte hain.
java
import [Link].*;
Important Points
• Agar class Serializable nahi implement karegi,
toh NotSerializableException aayega.
• Transient keyword: Kisi eld ko serialize nahi karwana hai toh
usko transient bana do.
• Static elds automatic serialize nahi hote hain.
Example (transient):
java
transient int temp; // Ye variable serialize nahi hoga
fi
fi
fi
fi
fi
fi
fi
Hinglish Summary Points
• Serialization: Object -> byte stream (save ya transfer ke liye).
• Deserialization: Byte stream -> object (wapas use karne ke liye).
• Serializable Interface: Zaroori hai class mein implement karna.
• File, network par transfer, caching ya remote method calls mein bahut
kaam aata hai.
Without serialization, aap Java objects ko le ya network par directly send/receive
nahi kar sakte.
java
import [Link].*;
Points to Remember
• transient sirf variables ke saath use hota hai, methods/classes ke saath
nahi.
• Default values serialization ke baad milti hain: objects ke liye null, int ke
liye 0, boolean ke liye false.
• Best practice hai con dential elds ko transient banana, especially
banking, login, ya security applications mein.
• Agar aap custom writeObject/readObject use karo to manually bhi
transient elds serialize kar sakte ho, par default behavior mein nahi hota.
Java mein thread ka life cycle ka matlab hai: ek thread apne creation se lekar
termination tak kin kin states se guzarta hai. Yeh states thread ke execution,
waiting, block hone aur terminate hone ko represent karti hain.
java
class DemoThread extends Thread {
public void run() {
[Link]("Thread is running - Running State");
try {
[Link](2000); // Timed Waiting State
} catch (InterruptedException e) {
[Link](e);
}
}
}
Q16) explain java8 features ( optional class, stream api, functional interface, default
keyword, lambda expression) ?
Java 8 mein kai powerful features aaye hain, jo coding ko modern, readable aur
e cient banate hain. Hinglish mein aur code ke sath, sab kuch step-by-step
explain kiya gaya hai: Optional class, Stream API, Functional Interface, Default
keyword, Lambda Expression.
1. Optional Class
• Kya hai?: NullPointerException bachane ke liye, ek wrapper class hai jo
value ki presence verify karti hai. Null check karne ki zarurat nahi padti.
• Use case: Jab value ayegi ki nahi, uncertain ho (method ke result,
property, etc).
• Code Example:
java
import [Link];
2. Stream API
fi
ffi
• Kya hai?: Collections (array, list, set) pe data ko functional style mein
process karne ka tarika— lter, map, reduce, sort, collect, etc.
• Use case: Large data processing, chaining operations.
• Code Example:
java
import [Link].*;
public class StreamDemo {
public static void main(String[] args) {
List<Integer> list = [Link](2, 7, 8, 1, 10, 5);
[Link]()
. lter(x -> x > 5)
.map(x -> x*x)
.forEach([Link]::println); // Output: 49 64 100 25
}
}
Data ko pipeline mein process kar sakte ho—easy and clean.
3. Functional Interface
• Kya hai?: Interface jisme ek hi abstract method hota hai (jaise Runnable,
Comparator).
• Use case: Lambda expression ka use, clean functional code.
• Code Example:
java
@FunctionalInterface
interface MyFunc {
void show();
}
4. Default Keyword
• Kya hai?: Ab interface ke methods ko default implementation de sakte ho
(optional override), pehle interface me only abstract methods possible tha.
• Use case: Backward compatibility, easy extension.
• Code Example:
java
interface Greetings {
default void hello() {
fi
fi
[Link]("Hello By Default!");
}
}
5. Lambda Expression
• Kya hai?: Functional interface ke liye ek concise way hai method ko
de ne karne ka—no need for extra class implementation.
• Use case: Anonymously function pass karna, especially stream/ lter/sort
ke sath.
• Code Example:
java
interface Square {
int get(int x);
}
java
import [Link];
java
import [Link];
fi
Function<Integer, Integer> square = x -> x * x;
[Link]([Link](7)); // 49
Yahan input number ka square nikal raha hai.
java
import [Link];
java
import [Link];
Java mein abstract class aur interface dono hi abstraction achieve karne ke liye use hote
hain, lekin dono ka design, use-case aur rules alag hote hain. Hinglish mein, detail aur
code ke saath sab kuch bataya gaya hai.
Abstract Class
• Abstract class ek base class hoti hai jo direct object nahi ban sakti; sirf inherit ki ja
sakti hai.
• Isme abstract (sirf declare kiye gaye, bina implementation ke) aur concrete
(implementation wale) methods dono ho sakte hain.
• Abstract class ke andar variables, constructors, aur normal methods bhi ho sakte
hain.
• Inheritance sirf ek hi abstract class se ho sakta hai (single inheritance).
Code Example:
java
abstract class Animal {
String name;
Animal(String name) {
[Link] = name;
}
abstract void makeSound(); // Abstract method
void eat() { // Concrete method
[Link](name + " is eating.");
}
}
Interface
• Interface ek set of completely abstract methods provide karta hai (Java 8 ke baad
default/static methods allowed ho gaye).
• Direct object nahi bana sakte, sirf implement kar sakte hain.
• Multiple interfaces ek hi class implement kar sakti hai (multiple inheritance
possible).
• Interface ke sab variables public, static aur nal hote hain by default.
Code Example:
java
interface Animal {
void makeSound();
default void eat() {
[Link]("Animal is eating (default)");
}
}
Default Methods Allowed (normal methods) Java 8 se interface mein bhi default
method allowed
Use when Common code reuse + 0-100% Pure abstraction (100%), contract
abstraction de nition
Keyword abstract class interface
java
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
double add(double a, double b) {
return a + b;
}
}
java
class Animal {
void sound() {
[Link]("Animal makes sound");
}
fi
fi
fi
ff
ff
}
Java Streams mein map() aur atMap() dono transformation ke liye use hote hain,
lekin dono ka behaviour (aur kaam) alag hai. Hinglish mein detail, code ke sath sab
kuch samjho.
1. map() Method
• Kya karta hai?: Har input element ko ek output element mein convert
(transform) karta hai—one-to-one mapping.
• Result: Stream mein jitne element input, utne hi output (size same rehta
hai).
• Use case: Kisi value ka square, uppercase, length nikalna, mapping
single value per element.
Simple Code:
java
List<String> names = [Link]("Amit", "Sumit", "Mohit");
// Uppercase har naam ko
List<String> upper = [Link]()
.map(String::toUpperCase)
.collect([Link]());
// Output: [AMIT, SUMIT, MOHIT]
Har element ka transformation simple hai, nested structure nahi banta.
2. atMap() Method
fl
ff
fl
fl
ffi
• Kya karta hai?: Har input element ko ek stream of elements (0, 1, or
many) mein convert karta hai aur phir sab streams ko ek single at stream mein
merge ( atten) kar deta hai—one-to-many mapping and attening.
• Result: Output streamlined ho jata hai, nested structure (List<List<>> ya
Stream<Stream<>>) single at stream ban jata hai.
• Use case: Nested collections, List of List ya String ko words/letters mein
todna.
Simple Code:
java
List<List<String>> data = [Link](
[Link]("A", "B"),
[Link]("C", "D", "E"),
[Link]("F")
);
// Output: [A, B, C, D, E, F]
Yahan map se each List ka stream milta, aur atMap se saare elements ek hi level
pe aa gaye, nested nahi.
java
List<String> lines = [Link]("hello world", "java code");
List<String> words = [Link]()
. atMap(line -> [Link]([Link](" ")))
.collect([Link]());
// Output: [hello, world, java, code]
Agar yahan map use hota toh Stream<Stream<String>> milta, atMap se proper
ek hi list aa jaati hai.
Java mein array aur ArrayList dono hi elements ka group store karne ke liye use
hote hain, lekin inke kaam karne ka tareeka, exibility, aur features bilkul alag hain.
Hinglish mein detail, code ke saath — sab samjho.
java
int[] marks = new int[5]; // Array of 5 integers
marks[0] = 90;
marks[1] = 85;
[Link](marks[1]); // 85
[Link]([Link]); // 5
java
import [Link];
ArrayList<Integer> marksList = new ArrayList<>();
[Link](90);
[Link](85);
[Link]([Link](1)); // 85
[Link]([Link]()); // 2
Yahan dynamically elements add/remove ho sakte hain.
Java mein ArrayList aur LinkedList dono List interface ke implementation hain,
lekin inka data store aur manipulation karne ka tareeka bilkul alag hai. Hinglish
mein detail, code, aur practical use-cases ke saath—sab kuch niche diya gaya hai.
ArrayList
• Kaise Store karta hai? Dynamic array ka use karta hai. Elements memory
me continuous locations par store hote hain.
• Access (get/set): Index-based fast access (O(1) time), random access
bahut e cient hai.
• Insertion/Deletion: Middle ya beginning me add/remove karna slow hota
hai, kyunki right ke sabhi elements ko shift karna padta hai (O(n) time).
• Memory: Kam memory use karta hai (bas data store hota hai).
• Best Use Case: Jab zyada access/search operations karne hain ya read-
heavy list chahiye.
Simple Code:
java
import [Link];
ArrayList<String> list = new ArrayList<>();
[Link]("Amit");
[Link]("Sumit");
[Link]([Link](1)); // Output: Sumit
LinkedList
• Kaise Store karta hai? Doubly linked nodes ke through elements ko point
karta hai. Har node aage aur peeche do nodes ko reference karta hai.
• Access (get/set): Index-based access slow hota hai (O(n)), har call pe
start/end se traverse karna padta hai.
• Insertion/Deletion: Beginning ya beech mein add/remove bahut fast (O(1)
agar node known ho), links update bas pointers badalte hain; shifting nahi hota.
• Memory: Zyada memory lagti hai (har node ke andar data + next/prev
pointers hote hain).
• Best Use Case: Jab aapko frequent insert/delete operations chahiye,
especially start ya middle mein.
Simple Code:
java
import [Link];
ffi
ff
fl
LinkedList<String> linkedList = new LinkedList<>();
[Link]("Amit");
[Link]("Sumit");
[Link]("Mohit"); // Fast insert at beginning
[Link]([Link](1)); // Output: Amit
Java mein HashMap aur Hashtable dono key-value pair store karte hain, lekin
dono ka kaam karne ka tareeka aur features alag hain. Hinglish mein detail, code,
aur important points niche diye gaye hain.
HashMap
• Kaise kaam karta hai?: Java Collections Framework ka part hai, map
interface implement karta hai, aur modern use ke liye recommend kiya jaata hai.
• Synchronization: Non-synchronized (thread safe nahi hai). Multiple
threads ke sath use karna ho toh external synchronization ya ConcurrentHashMap
prefer karo.
• Null Allow: Ek null key aur multiple null values allow karta hai.
• Performance: Faster than Hashtable (multi-threaded env mein aur bhi
fast ho sakta hai).
• Fail-fast Iterator: Agar map iteration ke dauraan modify hua toh
ConcurrentModi cationException mil sakta hai.
Code Example:
java
import [Link];
[Link]([Link](1)); // Amit
[Link]([Link](null)); // Mohit
Yahan null key/value kaam karta hai, aur normal print ho jaata hai.
Hashtable
• Kaise kaam karta hai?: Legacy class hai, Java 1.0 se aayi thi, Dictionary
ko extend karti hai (not part of Collections Framework, lekin Map implement karti
hai).
• Synchronization: Synchronized (thread safe hai). Sab methods
synchronized hain, isliye single-threaded application mein thoda slow hota hai.
• Null Allow: Null key/value allowed nahi hai (agar store karte ho toh
NullPointerException aayega).
• Performance: Relatively slow because synchronisation ka overhead rehta
hai.
• Enumerator: Iterator fail-fast nahi hota, enumerator use hota hai.
Code Example:
java
import [Link];
ff
fi
Hashtable<Integer, String> table = new Hashtable<>();
[Link](1, "Amit");
[Link](2, "Sumit");
// [Link](null, "Mohit"); // NullPointerException
// [Link](3, null); // NullPointerException
[Link]([Link](1)); // Amit
Yahan null key/value pe exception aa jaata hai.
HashMap
• Synchronization: Thread-safe nahi hai, single-threaded scenario ke liye
best hai.
• Null allowed: 1 null key aur multiple null values store kar sakte ho.
• Fail-fast: Agar map iterate karte waqt change kar diya, toh
ConcurrentModi cationException aata hai.
• Performance: Fastest choice jab sirf ek thread use kar raha ho; jab
concurrent update ho toh issues aa sakte hain.
• Usage: Jab thread-safety ki zarurat nahi ho, normal caching ya look-up
ke liye use karo.
Code Example:
java
import [Link];
HashMap<Integer, String> map = new HashMap<>();
[Link](1, "Amit");
[Link](2, "Sumit");
[Link](null, "Mohit"); // Null allowed
[Link]([Link](1));
ConcurrentHashMap
• Synchronization: Thread-safe hai, internally segment-level locking use
karta hai, jisse multiple threads ek sath safe tarike se kaam kar sakte hain (read aur
write dono).
• Null allowed: Null key ya null value bilkul bhi allow nahi hai—store karne
par NullPointerException aayega.
• Fail-safe: Iterators fail-safe hote hain—matlab, agar aap concurrent
update bhi karte raho toh ConcurrentModi cationException nahi aata.
• Performance: Thoda slow hai (compared to HashMap) because internal
locking, lekin high-concurrency mein best choice hai—zyada threads ek sath kaam
kar sakte hain bina block kiye.
• Usage: Jab aapko application multi-threaded ya concurrent access
chahiye (jaise web server cache, real-time updates).
Code Example:
java
import [Link];
ConcurrentHashMap<Integer, String> cmap = new ConcurrentHashMap<>();
[Link](1, "Amit");
[Link](2, "Sumit");
// [Link](null, "Mohit"); // NullPointerException
fi
fi
[Link]([Link](1));
java
class Student {
int roll;
String name;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != [Link]()) return false;
Student s = (Student) obj;
return roll == [Link] && [Link]([Link]);
}
@Override
public int hashCode() {
return 31 * roll + [Link]();
fi
ff
fi
}
}
Yahan:
• Doh students ka roll aur name same hai toh equals() true.
• Agar equals() true, toh hashCode bhi same ho hi jayega due to formula.
Usage in HashMap:
java
Student s1 = new Student(1, "Amit");
Student s2 = new Student(1, "Amit");
Java mein HashMap ek powerful data structure hai jo key-value pairs ko e ciently
store aur retrieve karta hai. Iska internal kaam “hashing” principle par based hai.
Yahan sab kuch Hinglish mein, easy explanation aur code snippet ke saath diya
gaya hai.
java
static class Node<K,V> {
nal int hash;
nal K key;
V value;
Node<K,V> next;
}
2. put() Operation
• Jab aap [Link](key, value) karte ho:
• Key ka hashCode() method call hota hai.
• HashMap array size se index calculate karta hai: index = hash %
arraySize.
• Us bucket par jaa kar dekhta hai:
• Agar bucket khali hai toh naya node insert kar dega.
• Agar pehle se entry hai (equals() se check hota hai), toh value update
hoti hai.
• Agar collision hai (same index), toh new node linked list ki tarah chain me
add hota hai.
• Java 8 se agar linked list me nodes jyada (>=8) ho jaate hain, toh wo
bucket tree mein convert ho jata hai fast search ke liye (O(log n) ).
3. get() Operation
• Jab aap [Link](key) karte ho:
• Key ka hashCode() nikala jata hai.
• index = hash % arraySize hota hai.
fi
fi
ffi
• Us index par linked list/ tree traverse hoti hai, har node pe equals() se
check hota hai, jab match milta hai toh us node ki value return hoti hai.
4. Collision Handling
• Do keys agar same bucket (same index) mein aa jaate hain toh unko
"collision" bolte hain.
• HashMap me collision ka handling separate chaining (linked list)/tree ed
(Java 8+) ke through hota hai.
5. Resizing/ Rehashing
• Jab HashMap ka size (number of elements/total buckets) 0.75 (default
load factor) cross kar jaata hai, toh array double kar di jati hai aur sari entries ko
nayi jagah move kiya jaata hai (rehashing).
• Isse performance O(1) near constant hi rehti hai.
6. Key Points
• HashCode() aur equals() properly override karna isliye zaruri hai taki data
access, insertion, search sahi ho.
• Null key ek allowed hai (index 0 par store hoti hai).
• Average time O(1). Agar sab keys colliding hain toh O(n) bhi ho sakta hai
(kabhi rare case).
• Fail-fast iterator hota hai (modi cation par exception aa sakta hai).
java
import [Link];
[Link]([Link]("Sumit")); // Retrieval
}
}
Yahan har key ke liye hash nikal ke, index kai bucket mein entry dalti/nikalti hai.
Java mein Comparable aur Comparator dono hi objects ko sort karne ke liye use
hote hain, magar dono ka use-case aur implementation tareeka alag hota hai.
Hinglish mein, di erence, explanation aur code ke sath sab kuch niche diya gaya
hai.
Comparable Interface
• Comparable interface ko apni class mein implement karna padta hai.
• Isme ek hi method hota hai: compareTo(Object o) – yeh current object
ko dusre object ke saath "natural order" mein compare karta hai.
• Default sorting provide karta hai (Jaise Student roll number, Name,
Employee Salary — ek hi rule rahega).
• Sirf ek sorting logic ho sakta hai — baar baar alag tareeke se sort nahi
kar sakte bina compareTo logic badle.
ff
ff
ffi
Code Example:
java
class Student implements Comparable<Student> {
int roll;
String name;
Comparator Interface
• Comparator external logic provide karta hai — yeh alag class/
anonymous class/ lambda expression ke through bana sakte ho.
• Isme compare(Object o1, Object o2) method hota hai — do objects ko
compare karta hai custom rule ke basis pe.
• Multiple sorting rules possible hain (Jaise roll, name, marks, salary, etc.),
bina original class modify kiye.
Code Example:
java
class Student {
int roll;
String name;
Student(int roll, String name) {
[Link] = roll;
[Link] = name;
}
}
public class Test {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
[Link](new Student(3, "Amit"));
[Link](new Student(1, "Sumit"));
[Link](new Student(2, "Mohit"));
Java mein ArrayList aur Vector dono hi dynamic arrays hain jo List interface
implement karte hain, lekin unke beech kuch important di erences hote hain.
Hinglish mein, unka detail comparison, code with examples, aur use-cases niche
diya gaya hai.
Code Example
java
import [Link];
import [Link];
// Vector example
Vector<String> vector = new Vector<>();
[Link]("Mohit");
[Link]("Suresh");
[Link]("Vector: " + vector);
}
}
Static Method
Non-Static Method
Java mein access modi ers ka use classes, variables, methods, aur
constructors ki visibility decide karne ke liye hota hai. Yani, kaun-
kaun se part code ke accessible hai, aur kis scope mein cheezein
visible hongi. Hinglish mein detailed explanation, saare types aur
code examples yahan diye gaye hain.
• Jab koi modi er nahi use karte, toh default hota hai.
• Sirf same package ke andar code accessible hota hai. Outside
package, visible nahi hota.
Example:
java
class Demo {
int value = 10; // default
void show() { [Link](value); }
}
Yahan value aur show() method sirf iss package ke andar hi access
ho sakte hain, package ke bahar nahi.
3. Protected
4. Public
Java mein wait() aur sleep() methods dono threads ko temporarily pause karne ke
liye use hote hain, lekin inka kaam, location, aur behavior bilkul alag hai. Hinglish
mein, detail + examples niche diye gaye hain.
1. sleep() Method
fi
• Thread class ka static method hai: Directly [Link]() likh ke call kar
sakte ho.
• Kahan use hota?: Sirf current thread ko speci ed time (milliseconds) ke
liye pause karta hai, chahe synchronized block ho ya nahi.
• Lock/Monitor: Sleep karte waqt thread ka lock/reentrant monitor release
nahi hota. Dusre threads synchronized block mein nahi aa sakte.
• Resumption: Sleep khatam hote hi thread dubara runnable ho jata hai,
kisi aur thread ka noti cation nahi chahiye.
• Exception: Checked exception hai, isliye try-catch zaroori hai.
Code Example:
java
class Demo {
public static void main(String[] args) throws InterruptedException {
[Link]("Sleeping... " + [Link]());
[Link](2000); // 2 second sleep
[Link]("Awake! " + [Link]());
}
}
Yahan thread 2 seconds rukke r continue karega.
2. wait() Method
• Object class ka non-static method hai: Sirf object ke synchronized block/
method ke andar se hi call kar sakte ho.
• Kahan use hota?: Inter-thread communication ke liye—ek thread dusre ki
noti cation ka wait karta hai.
• Lock/Monitor: Wait call karte hi thread apna lock release kar deta hai, taki
dusre threads synchronized block ko enter kar sakein.
• Resumption: Wait se bahar only tab aayega jab notify()/notifyAll() kisi
dusre thread se call ho (ya time-out ho).
• Exception: Checked exception hai.
Code Example:
java
class Demo {
public static void main(String[] args) throws InterruptedException {
nal Object obj = new Object();
Thread t = new Thread(() -> {
synchronized(obj) {
try {
[Link]("Thread waiting...");
[Link]();
[Link]("Thread resumes!");
} catch (InterruptedException e) {}
}
});
[Link]();
fi
fi
fi
fi
fi
[Link](2000); // Give above thread a little time to start and wait
synchronized(obj) {
[Link](); // Notify the waiting thread
}
}
}
Yahan ek thread wait karega, dusra thread usko notify karke resume karega.
Java mein try-with-resources ek special try block hai jo resource (jaise le, stream,
socket, database connection) ko automatically close kar deta hai, bina aapko
nally mein manually close likhna padhe. Ye feature Java 7+ mein aaya, aur
resource leak (memory issues, open les) avoid karne ke liye use hota hai. Hinglish
mein full explanation, real code, aur key points yahan diye gaye hain.
fi
ff
fi
fi
Try-with-Resources — Concept
• Resource matlab koi aisa object jo system resource use karta ho ( le,
stream, socket…) aur jisko close karna zaruri hota hai.
• Mechanism: Agar resource (like FileInputStream, Bu eredReader, etc.)
AutoCloseable interface implement karta hai, toh JVM try block ke end par
automatically close() method call kar deti hai.
• Purpose: Resource leak se bachna; clean aur safe code likhna.
java
import [Link].*;
java
try (Scanner scanner = new Scanner(new File("[Link]"));
PrintWriter writer = new PrintWriter(new File("[Link]"))) {
while ([Link]()) {
[Link]([Link]());
}
}
// Dono resources — scanner, writer — automatically close ho jayenge, koi memory
leak nahi[web:338][web:345].
Key Points
• AutoCloseable required: Sirf wahi class resource ban sakti hai jo
AutoCloseable implement karti ho (like InputStream, OutputStream, Reader, Writer,
Scanner, Connection etc.).
ff
ff
fi
ff
fi
• No need for nally: Manual [Link]() likhne ki zarurat nahi, JVM
handle karta hai.
• Exception handling: Agar exception aaye toh bhi resource close ho
jayega.
• Multiple resources: Semicolon (;) se resources declare karein, sab
automatically close ho jayenge reverse order mein.
• Java 9 se: Resource ko try ke bahar bhi declare karke block ke andar
refer kar sakte hain.
Java mein constructor ek special method hota hai jo object create hote hi run hota
hai, aur object ki initial state set karta hai (jaise variables ko value dena).
Constructor ka naam class ke naam jaisa hota hai, koi return type nahi hota, aur ye
fi
ff
fi
fi
fi
automatic call ho jaata hai jab bhi new keyword se object banta hai. Hinglish mein,
concept, types, aur har ek ka code example niche diya gaya hai.
java
class Student {
int roll;
String name;
// Constructor
Student() {
[Link]("Constructor called!");
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student(); // "Constructor called!" print hoga
}
}
Types of Constructors
1. Default Constructor
• Ye tab call hota hai jab aap khud koi constructor nahi likhte—compiler
apne aap bana deta hai (no-arg, khali body).
• Object ke variables ko default value deta hai.
Example:
java
class Car {
String model;
// Koi constructor de ne nahi kiya
}
public class Test {
public static void main(String[] args) {
Car c = new Car(); // Default constructor call
[Link]([Link]); // null
}
}
3. Parameterized Constructor
• Isme arguments hote hain, object create karte waqt custom values de
sakte hain.
• Flexible initialization ke liye use hota hai.
Example:
java
class Car {
String model;
int year;
Car(String m, int y) { // Parameterized constructor
model = m;
year = y;
}
}
public class Test {
public static void main(String[] args) {
Car c = new Car("Swift", 2020);
[Link]([Link] + " " + [Link]); // Swift 2020
}
}
java
class Car {
String model;
Car(Car c) { // Copy constructor
[Link] = [Link];
}
}
public class Test {
public static void main(String[] args) {
Car c1 = new Car();
[Link] = "Creta";
Car c2 = new Car(c1);
[Link]([Link]); // Creta
}
}
Java mein StringBu er aur StringBuilder dono mutable classes hain, yani inmein jo
value hoti hai, usko bina naya object banaye modify kar sakte ho. Lekin in dono ka
main di erence unka synchronization, performance aur use-case hai. Hinglish mein
detail, example aur important points niche milenge.
StringBu er
• Thread-Safe: StringBu er ka har method synchronized hota hai, matlab
multiple threads jab ek object pe kaam karte hain, toh data corrupt nahi hoga.
• Performance: Thoda slower hota hai kyunki synchronization ka overhead
rehta hai.
• Use-case: Jab application multi-threaded hai, ya ek hi string ko multiple
threads modify kar rahe hain (banking, server requests etc).
fi
ff
ff
fi
ff
ff
ff
ff
• Introduced in: Java 1.0.
Code Example:
java
public class Demo {
public static void main(String[] args) {
StringBu er sb = new StringBu er("Hello");
[Link](" World");
[Link](5, " Java");
[Link]();
[Link](sb); // Output: dlroW avaJ olleH
}
}
Yahan sb ko modify kar rahe hain, naya object nahi bana.
StringBuilder
• Not Thread-Safe: Iske methods synchronized nahi hote, toh agar ek hi
object multiple threads se access ho toh data corrupt ho sakta hai.
• Performance: Zyada fast hota hai (single-threaded applications mein).
Synchronization nahin hone ki wajah se speed zyada hai.
• Use-case: Jab string manipulation sirf ek thread mein ho (interview code,
utility, string parsing etc).
• Introduced in: Java 1.5.
Code Example:
java
public class Demo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link](5, " Java");
[Link]();
[Link](sb); // Output: dlroW avaJ olleH
}
}
Same methods hain, bas thread safety nahi hai.
Synchronization ka Concept
• Basic Point: Ek waqt me sirf ek thread hi shared resource access kare,
dusre thread ko wait karna pade.
• Lock/Monitor: Java objects ke saath ek lock hoti hai — jo thread ko lock
acquire karna padta hai, taaki koi dusra thread tab tak access na kar sake.
• Use Cases: Banking transactions, ticket booking, inventory updates,
shared le access, etc.
java
class Book {
int total = 10;
fi
ff
fi
ff
ff
ff
public synchronized void bookTicket() {
if (total > 0) {
[Link]("Booking ticket, remaining: " + (--total));
} else {
[Link]("No tickets left");
}
}
}
public class Test {
public static void main(String[] args) {
Book b = new Book();
Thread t1 = new Thread(() -> { for(int i=0; i<5; i++) [Link](); });
Thread t2 = new Thread(() -> { for(int i=0; i<5; i++) [Link](); });
[Link](); [Link]();
}
}
Yahan dono thread synchronized method ko access karte hain, ek ek karke.
2. Synchronized Block
• Sirf shared resource ke chakkar mein lock lagate hain.
• Object ya class ke lock se resource ko protect karte hain.
Example:
java
class Ticket {
int tickets = 5;
Object lock = new Object();
Why Synchronize?
• Race Conditions: Jab multiple threads same data modify karne ki
koshish karte hain.
• Data Integrity: Sahi result ke liye resource ko lock karna jaruri hai.
• Data Loss: Multiple thread simultaneously update kar rahe hain toh data
corrupt ho sakta hai.
fi
Example - Ticket Booking System
java
class TicketBooking {
private int availableTickets = 10;
Summary (Hinglish)
• Synchronization ka matlab: sirf ek thread hi shared resource ko access
kare, doosra wait kare.
• Methods: Synchronized method ya synchronized block.
• Use: Data race, corruption rokne ke liye, jaise money transfer, ticket
booking.
• Thread safety achieved karne ke liye bahut zaruri hai inka sahi use.
Aggregation
class Department {
String name;
List<Student> students; // Aggregation (reference)
Department(String name, List<Student> students) {
[Link] = name;
[Link] = students;
}
}
Yahan department students ka reference rakhta hai, lekin students
khud se exist kar sakte hain.
Composition
class House {
private List<Room> rooms;
House() {
rooms = new ArrayList<>();
[Link](new Room("Living Room"));
[Link](new Room("Bedroom"));
}
}
Yahan House apne Rooms ko create karta hai aur unka ownership
rakhta hai; house ke bina rooms nahi exist kar sakte.
Syntax
java
@FunctionalInterface
interface CustomInterface {
void display();
}
java
@FunctionalInterface
interface Calculator {
fi
int operation(int a, int b);
}
Key Points
• Functional interface mein default ya static methods ho sakte hain, lekin
sirf ek abstract method hona chahiye.
• @FunctionalInterface annotation optional hai, lekin use karna
recommended hai taaki compiler check kar sake.
• Lambda expressions ke saath functional interfaces concise aur clean
code likhne mein madad karte hain.
• Aap apni need ke hisaab se custom functional interfaces bana kar
reusability badha sakte hain.
Java mein Singleton Class ek design pattern hai jo ye ensure karta hai ki us class
ka sirf ek hi object (instance) create ho aur puri application mein wohi object reuse
ho. Iska matlab ye hai ki aap har jagah usi ek instance ko access karoge, new
object create nahi karoge. Yeh pattern mostly resource control, caching, logger ya
con guration purpose ke liye use hota hai. Hinglish mein pure concept, types of
singleton creation, aur code example niche hai.
java
public class EagerSingleton {
private static nal EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {} // private constructor
java
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
fi
fi
fi
public static LazySingleton getInstance() {
if(instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
java
public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
private ThreadSafeSingleton() {}
java
public class BillPughSingleton {
private BillPughSingleton() {}
Summary Table
Feature Eager Lazy Thread-safe Bill Pugh
Singleton Singleton Singleton Singleton
Instance Class loading First request First request Lazy + thread
Creation pe pe pe (sync) safe (static
inner class)
Thread Safety Haan Nahi Haan Haan
Performance Fast Fast Thoda slow Fast
Complexity Simple Simple Simple Modern best
practice
Singleton design pattern Java mein commonly use hota hai for controlled object
creation and resource management
fi
Q1) Types of inheritance java support ?
ava mein inheritance ek aisa concept hai jisme ek class (child/subclass) doosri
class (parent/superclass) ke features ko inherit karti hai. Isse code reusability,
maintainability, aur OOP structure improve hota hai. Java mainly teen types ke
inheritance support karta hai (class ke through): Single, Multilevel,
aur Hierarchical. Multiple inheritance classes ke case mein direct support nahi hai,
lekin interfaces se achieve kiya ja sakta hai. Hinglish mein sab kuch with code
yahan diya gaya hai.
1. Single Inheritance
• Ek subclass ek hi superclass se inherit karta hai.
• Sabse common aur basic form hai.
• Example: Dog extends Animal
Code Example:
java
class Animal {
void eat() { [Link]("Eating..."); }
}
2. Multilevel Inheritance
• Ek class doosri class se inherit karti hai, aur usse aage ek aur class
inherit karti hai (direct lineage).
• Example: Labrador extends Dog extends Animal
Code Example:
java
class Animal {
void eat() { [Link]("Eating..."); }
}
class Dog extends Animal {
void bark() { [Link]("Barking..."); }
}
class Labrador extends Dog {
void play() { [Link]("Playing..."); }
}
3. Hierarchical Inheritance
• Ek parent class ko multiple child classes inherit karte hain (tree structure).
• Example: Animal ko Dog, Cat, Cow inherit karte hain.
Code Example:
java
class Animal {
void eat() { [Link]("Eating..."); }
}
class Dog extends Animal {
void bark() { [Link]("Barking..."); }
}
class Cat extends Animal {
void meow() { [Link]("Meowing..."); }
}
class C implements A, B {
public void showA() { [Link]("A"); }
public void showB() { [Link]("B"); }
}
1. Lambda Expressions
• Kya hai?: Anonymous function ya method, bina naam ke — concise aur
short code likhne ke liye.
• Kyuse hota hai?: Functional interface ke liye function pass kar sakte ho,
event handling, collection processing, etc.
• Syntax Example:
java
Runnable r = () -> [Link]("Hello Java 8");
• [Link]();
•
java
@FunctionalInterface
• interface MyFunc { void show(); }
• MyFunc mf = () -> [Link]("Custom Functional Interface");
• [Link]();
•
3. Method References
• Kya hai?: Existing method ko reference ke through use karna, lambda ki
tarah concise code.
• Syntax Example:
java
Consumer<String> printer = [Link]::println;
• [Link]("Printed via Method Reference");
•
4. Stream API
• Kya hai?: Collection pe functional style mein data process karne ka tarika
— lter, map, reduce, sort, collect, etc.
• Kyuse hota hai?: List, Set, Array ko pipeline style mein transform/process
karne ke liye.
• Example:
java
List<Integer> nums = [Link](2, 3, 5, 6, 7);
fi
fi
fi
• [Link](). lter(x -> x%2==0).map(x ->
x*x).forEach([Link]::println);
•
5. Optional Class
• Kya hai?: NullPointerException bachane ke liye — value present hai ya
nahi safely check kar sakte ho.
• Kyuse hota hai?: Null safe programming, safer method returns, null
checks avoid karne ke liye.
• Example:
java
Optional<String> name = [Link](null);
• [Link]([Link]()); // false
• [Link]([Link]("Default")); // Default
•
Yahan agar value nahi hai toh default safely mil jaata hai.
java
interface Greeting {
• default void hello() { [Link]("Hello from default!"); }
• static void staticMethod() { [Link]("Static hello!"); }
• }
•
java
LocalDate today = [Link]();
• LocalDate birthday = [Link](2000, 05, 22);
• Period age = [Link](birthday, today);
• [Link]("Age: " + [Link]());
•
8. Other Features
• Base64 Encoding/Decoding: Data encryption/decryption ke liye direct
support.
• Parallel Streams: Large data ko multi-thread mein process kar sakte ho
for better performance.
• Nashorn JavaScript Engine: JavaScript directly Java app ke andar run
kar sakta hai.
• Files and Path API Updates: Files class mein nayi methods — create,
move, delete, copy ( lesystem work fast ho gaya).
Java mein interface ke andar private variable banana possible nahi hai, chahe Java
ka koi bhi version ho. Interface ke andar variables hamesha public, static aur
nal (constants) hote hain by default. Matlab, agar aap variable declare karte ho to
vo public static nal hi mana jayega, aur private variable declare karne par
fi
fi
fi
compilation error aayega. Yeh cheez Java ke sabhi versions pe lagu hoti hai (Java
8, 9, 17, 21, etc.).
java
interface DemoInterface {
// Valid - public static nal by default
int VALUE = 10;
java
interface MyInterface {
default void show() {
display(); // call private method inside interface
}
private void display() {
[Link]("This is a private method in interface!");
}
}
Java 8 se interface mein default aur static methods ka concept introduce hua hai.
Dono ka kaam aur reason alag hai, lekin ek common goal hai: Java code ko
modern, backward compatible aur exible banana. Hinglish mein di erence,
reasons, aur code example yahan diya gaya hai.
java
interface Vehicle {
• default void honk() {
• [Link]("Beep!");
• }
• }
•
• class Car implements Vehicle {}
•
• public class Test {
• public static void main(String[] args) {
• Car c = new Car();
• [Link](); // Output: Beep!
• }
• }
•
fi
fl
fi
ff
Yahan implementing class ko kuch bhi override nahi karna pada, r bhi interface ka
default method mil gaya.
java
interface Vehicle {
• static String getVehicleType() {
• return "Generic Vehicle";
• }
• }
•
• class Car implements Vehicle {}
•
• public class Test {
• public static void main(String[] args) {
• [Link]([Link]()); // Output: Generic
Vehicle
• // [Link](); // Error!
• }
• }
•
Q5) How exception handled ? what will happen in basic ow ? di erent exception
starting from base class ? Hierarchy as well ?
Java mein exception handling ek mechanism hai jisse program errors (unexpected
conditions) ko handle karke program ko crash hone se bachaya ja sakta hai.
Exception handling try-catch- nally ow ke through kaam karta hai. Sabhi
exception classes ek base class (Throwable) ke niche aati hain, jiska ek
hierarchical structure hota hai. Hinglish mein, full ow, hierarchy, aur code example
niche diya gaya hai.
java
public class Demo {
public static void main(String[] args) {
try {
int a = 10/0; // ArithmeticException hoga
fi
fl
fl
fl
ff
[Link]("After exception"); // Ye line skip hogi
} catch(ArithmeticException e) {
[Link]("Exception handled: " + e);
} nally {
[Link]("Finally block always runs");
}
[Link]("Program continues...");
}
}
Output:
text
Exception handled: [Link]: / by zero
Finally block always runs
Program continues...
text
Object
└── Throwable
├── Error
└── Exception
├── RuntimeException (Unchecked)
└── Other Exceptions (Checked)
Common Exception Types:
• Checked: IOException, SQLException, ClassNotFoundException
• Unchecked: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, IllegalArgumentException
• Error: OutOfMemoryError, StackOver owError, AssertionError
3. Try-Catch-Finally Flow
• try: Risky code yahan likhte hain.
• catch: Exception handle karne ke liye.
• nally: Resource cleanup — hamesha chalega.
Example with multiple catch:
java
fi
fi
fi
fl
fl
try {
String s = null;
[Link]([Link]()); // NullPointerException
} catch(NullPointerException e) {
[Link]("Null object accessed!");
} catch(Exception e) {
[Link]("General exception: " + e);
} nally {
[Link]("Cleanup done!");
}
Example Code
java
// Abstract class Shape
abstract class Shape {
String name;
Shape(String name) {
[Link] = name;
}
// Concrete method
public void showName() {
[Link]("Shape name: " + name);
}
// Abstract methods
abstract double area();
abstract void draw();
}
// Subclass: Rectangle
class Rectangle extends Shape {
int length, width;
Rectangle(String name, int l, int w) {
super(name);
length = l; width = w;
fi
fi
}
double area() { return length * width; }
void draw() { [Link]("Rectangle drawn!"); }
}
// Subclass: Circle
class Circle extends Shape {
int radius; nal double pi = 3.14;
Circle(String name, int r) {
super(name);
radius = r;
}
double area() { return pi * radius * radius; }
void draw() { [Link]("Circle drawn!"); }
}
Java mein nally block ek special section hai jo exception handling (try-catch)
structure mein use hota hai. Iska main purpose hai — resource cleanup ya
guaranteed execution, chahe exception aaye ya na aaye, ya program ka ow kahi
pe break ho jaye. Hinglish mein detail explanation aur code sab kuch yahan hai.
java
try {
// risky code yahan likho
} catch(ExceptionType e) {
// exception handle karo
} nally {
// always execute hone wala code
}
java
public class FinallyExample {
public static void main(String[] args) {
try {
int data = 50 / 0; // ArithmeticException hoga
[Link]("Try block code");
} catch(ArithmeticException e) {
[Link]("Exception caught: " + e);
} nally {
[Link]("Finally block always executed");
}
[Link]("Program continues...");
}
}
Output:
text
Exception caught: [Link]: / by zero
Finally block always executed
Program continues...
Yahan nally block exception ke baad bhi mandatory execute hoga.
java
public class FinallyOnlyTry {
fi
fi
fi
fi
public static void main(String[] args) {
try {
[Link]("Inside try block");
} nally {
[Link]("Finally block executed");
}
}
}
Yahan catch nahi hai, r bhi nally block chalega.
java
import [Link].*;
Java Streams ke through objects ko unke kisi speci c eld jaise "%", ya kisi bhi
numeric eld ke basis pe sort karna bahut easy hai. Hinglish mein clear
explanation aur code example deta hoon jisme objects ko "percentage" eld ke
basis pe sort karenge.
java
import [Link].*;
import [Link].*;
class Student {
String name;
double percentage;
Output
text
Sorted by percentage ascending:
Mohit: 68.9%
Amit: 75.5%
Sumit: 82.3%
Rohit: 90.0%
Java streams se sorting ka yeh tareeka modern aur best practice maana jata hai,
especially large datasets ya functional programming ke liye.
Java mein memory leak tab hota hai jab program memory allocate karta hai par
usko wapas free nahi karta, jis wajah se memory gradually bhar jaata hai aur
eventually OutOfMemoryError throw hota hai. Java garbage collector automatic
memory free karta hai, lekin memory leak uss case mein hota hai jab object ka
reference unnecessarily maintain kiya jaata hai, isliye GC us object ko free nahi kar
pata. Hinglish mein pura concept, causes, aur example niche diya gaya hai.
java
class Animal {
void eat() {
[Link]("Animal eats food");
}
}
class Dog extends Animal {
void bark() {
fi
fi
fl
[Link]("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Animal ke method
[Link](); // Dog ke method
}
}
java
class Animal {
void sound() { [Link]("Animal makes sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Dog barks"); }
}
class Cat extends Animal {
fi
ff
void sound() { [Link]("Cat meows"); }
}
public class Test {
public static void main(String[] args) {
Animal a1 = new Dog(); // Animal reference, Dog object
Animal a2 = new Cat(); // Animal reference, Cat object
[Link](); // Outputs: Dog barks
[Link](); // Outputs: Cat meows
}
}
Yahan same method sound() di erent objects ke liye alag function perform karta
hai.
Summary (Hinglish):
Concept Explanation Example/Use
Case
Inheritance "Is-A" Animal -> Dog,
(Types) relationship, Animal -> Cat
code reuse,
extend existing
classes
Polymorphism Ek method sound() metho
(Types) alag classes d across
mein di erent Animal, Dog,
behavior, Cat classes
runtime
selection
Major use Code Abstracts
reusability, common
exibility, code behavior;
maintenance speci c
behavior
override
Final notes:
Inheritance se hum ek common base bana sakte hain, aur polymorphism se
runtime pe di erent behaviors perform kar sakte hain. Java mein ye dono core
pillars hain, ye samajh ke implementation karo toh code clean, scalable aur exible
banega.
Agar detailed example chahiye to speci c scenario batao, main uske hisaab se
code aur explanation de dunga!
fl
fi
ff
ff
ff
fi
fl
Q11) explain static and default method in interfaces ?
Java 8 se interface mein static aur default methods ke concepts introduce hue
hain. Ye dono methods interface mein add karne ki exibility provide karte hain, jo
pehle Java ke versions (Java 7 se pehle) mein sirf abstract methods (method
signatures) ki hi limitation thi. Hinglish mein inka explanation, purpose, aur code
examples ke sath sab kuch yahan hai.
1. Default Method
Kya hai?:
Default method ek aisa method hai jiska body interface ke andar hota hai. Isko
implement karne wale classes override kar sakti hain, par override na bhi karein
toh bhi default implementation chalega.
Use-case?:
Existing interfaces ko bina purane implementation ko torde naye features add
karne ke liye. Agar koi class default method ko override na kare toh bhi chal jata
hai.
Syntax:
java
interface Vehicle {
default void honk() {
[Link]("Beep from default honk");
}
}
class Car implements Vehicle {}
2. Static Method
Kya hai?:
Static method interface me bhi de ne kiya ja sakta hai. Ye class ke static methods
jaise hota hai, jise directly interface ke naam se call kiya jata hai. Iska koi override
nahi hota implementation class me.
Use-case?:
Utility functions ya helper methods jo ki shared code ho, jise multiple classes use
kar sake.
Syntax:
fi
fl
java
interface MathOperations {
static int add(int a, int b) {
return a + b;
}
}
public class Test {
public static void main(String[] args) {
[Link]([Link](10, 20)); // Output: 30
}
}
Note:
• Static methods interface ke andar hi de ne hoti hain, class me override
nahi hoti.
• Call karna bhi sirf [Link]() se hota hai.
Conclusion
Interface me default methods object ke sath call hoti hain aur override ki ja sakti
hain; static methods interface ke static utility functions hoti hain, jinhe directly
interface ke naam se call kiya jata hai. Boris simple term me: Default = object ke
through, override ye kar sakti hai; Static = class-level, override nahi hoti.
Ye concept Java programming me bahut bada step hai, aur exam/interview ke liye
bahut important hai.
[Link]();
[Link]();
[Link]();
[Link]();
2. Synchronized Block
• Sirf critical section ko synchronize karna ho toh synchronized block ka
use karte hain.
fi
• Isme lock ke liye object specify karna hota hai (object jiski lock leni hai).
Example:
java
class Printer {
private nal Object lock = new Object();
Summary (Hinglish)
Feature Explanation
Synchronizatio Multiple
n threads ko
shared
resource safe
share karvana
synchronized Complete
method method lock
kar deta hai
synchronized Sirf speci c
block code block ko
lock karta hai
Lock Details Non-static
method ->
object lock;
static method
-> class lock
fi
fi
Use-case Data
consistency,
race condition
rokna
Downsides Performance
degrade ho
sakti hai,
deadlock risk
Interview Tips
• Real life examples dijiye jaise banking transaction, ticket booking.
• Thread se related problems samjhaiye jaise race condition, thread
interference.
• Synchronization ka impact aur alternative solutions bhi bataye (e.g.
concurrent package).
Synchronization Java ke multithreading mein bahut zaruri
feature hai jisse thread-safe programs banate hain
Java mein logging ko check karne ke kai tareeke hote hain, aur ye depend karta
hai aap kis logging framework ka use kar rahe hain aur aapke logger ka
con guration kya hai. Hinglish mein basic Java logging setup aur log check karne
ka process samjhata hoon, simple examples ke saath.
java
import [Link].*;
java
try {
FileHandler fh = new FileHandler("[Link]", true);
[Link](fh);
SimpleFormatter formatter = new SimpleFormatter();
[Link](formatter);
java
import [Link];
Agar aapko kisi speci c framework mein logging karna hai, ya advanced
con gurations chahiye mean help ka request karo. Java logging se aap easily
bugs, errors, aur execution ka track rakh sakte hain.
2. toSet()
• Stream elements ko Set mein collect karta hai.
• Duplicate remove ho jate hain kyunki Set unique hota hai.
Example:
java
Set<String> uniqueNames = [Link]("Amit", "Sumit", "Amit")
.collect([Link]());
[Link](uniqueNames);
// Output: [Amit, Sumit]
3. toMap()
• Stream elements se Map banata hai.
• Key aur Value supplier functions pass kar sakte hain.
Example:
java
Map<String, Integer> map = [Link]("Amit", "Sumit", "Mohit")
.collect([Link](name -> name, name -> [Link]()));
[Link](map);
// Output: {Amit=4, Sumit=5, Mohit=5}
4. joining()
• Stream elements ko string ke roop mein join karta hai.
• Separator, pre x, su x specify kar sakte hain.
Example:
java
String joined = [Link]("Amit", "Sumit", "Mohit")
.collect([Link](", ", "[", "]"));
[Link](joined);
// Output: [Amit, Sumit, Mohit]
5. groupingBy()
• Elements ko banate hain groups mein kisi classi er function ke basis par.
• Result Map<Key, List<Value>> return karta hai.
Example:
java
List<String> names = [Link]("Amit", "Sumit", "Ankit", "Mohit");
Map<Character, List<String>> grouped = [Link]()
.collect([Link](name -> [Link](0)));
fi
ffi
fi
[Link](grouped);
// Output: {A=[Amit, Ankit], S=[Sumit], M=[Mohit]}
6. partitioningBy()
• Elements ko do groups mein separate karta hai, true ya false classi er ke
basis par.
• Result Map<Boolean, List<Value>> deta hai.
Example:
java
List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6);
Map<Boolean, List<Integer>> partitioned = [Link]()
.collect([Link](n -> n % 2 == 0));
[Link](partitioned);
// Output: {false=[1, 3, 5], true=[2, 4, 6]}
java
List<Integer> nums = [Link](1, 2, 3, 4, 5);
int sum = [Link]().collect([Link](Integer::intValue));
double avg = [Link]().collect([Link](Integer::intValue));
long count = [Link]().collect([Link]());
[Link]("Sum: " + sum + ", Avg: " + avg + ", Count: " + count);
// Output: Sum: 15, Avg: 3.0, Count: 5
Hinglish Summary
• Collectors stream ke elements ko collections (List, Set, Map) me convert
karne, string join karne aur statistics nikalne ke liye pre-built static methods
provide karta hai.
• Common
methods: toList(), toSet(), toMap(), joining(), groupingBy(), partitioningBy(), su
mmingInt(), averagingInt(), counting().
• Streams + Collectors se functional aur concise collection manipulation
possible hota hai.
Java streams aur Collectors class ka istemal aapke code ko simplify karta hai aur
powerful bana deta hai. Interview mein Collectors ke ye common methods
samajhna aur apply karna zaruri hai.
fi
A HashMap consists of an array of buckets where each bucket represents a linked list or a tree structure to manage collisions . Operations such as put() calculate the bucket index using hashCode and the modulus operation to determine where to store or retrieve data. If multiple keys hash to the same index, often called a collision, they are placed in a list/tree at that bucket's index . HashMap resizes (doubles in capacity) when the threshold of its load factor (default 0.75) is crossed, which triggers rehashing of all existing entries . This ensures near constant O(1) average time complexity for operations.
The contract between equals() and hashCode() ensures that two equal objects must have the same hashCode but different hashCodes must ensure inequality . This is crucial in hash-based collections like HashMap or HashSet because these structures rely on hashCode() for indexing and equals() for equality checks. Violating this contract can lead to issues like data not being retrievable or duplicates entering collections, which compromises collection integrity and retrieval efficiency .
The sleep() method belongs to the Thread class and is used to pause the execution of the current thread without releasing any locks held by the thread. It is often used for timing and delays . Conversely, the wait() method is part of the Object class and is used for inter-thread communication within synchronized block/methods, releasing the held object's lock until notified by another thread's notify() or notifyAll() call . This makes wait() critical for synchronized communication as opposed to sleep(), which interrupts execution for fixed periods without affecting synchronization.
Try-with-resources in Java ensures that each declared resource within the try statement is closed automatically at the end of the statement block, minimizing resource leaks without needing a finally block . This feature requires the resources, such as streams and files, to implement the AutoCloseable interface. It significantly simplifies code readability and safety by managing resource deallocation, reducing boilerplate for exception handling, and ensuring efficient resource management .
HashMap is not thread-safe and designed for single-threaded applications, while ConcurrentHashMap is thread-safe and ideal for concurrent, multithreaded environments . HashMap uses a simple structure which makes it fast under single-threaded conditions, but it can encounter synchronization problems and exceptions like ConcurrentModificationException in multithreaded uses . ConcurrentHashMap, however, is optimized for concurrent operations with features like lock segmentation to maintain efficiency and prevent exceptions due to concurrent modifications .
Java iterators implement fail-fast behavior by throwing a ConcurrentModificationException if the underlying collection is structurally modified at any time after the iterator is created, except through the iterator's own remove method. This occurs because iterators track modifications using a modCount that must match the expected count during an iteration process . While this mechanism provides immediate feedback on illegal concurrent modifications that can lead to errors, it also requires developers to carefully manage collection modifications during iterations to avoid runtime exceptions, reinforcing disciplined usage of collections in multithreading contexts.
Synchronization in Java ensures that only one thread at a time can access a critical section of code or a shared resource by acquiring a lock associated with the object or class. This prevents data races and inconsistencies when multiple threads attempt to modify a shared variable . Synchronization can be achieved through synchronized methods, which acquire the lock on the object method invocations, or through synchronized blocks which allow finer-grained control by synchronizing specific sections inside methods . This avoids anomalies in data and ensures thread-safe operations.
The Comparable interface is implemented in the class whose instances need a natural ordering, using the compareTo() method to define the sort logic based on instance fields like roll number or name . This approach restricts sorting to one scenario since compareTo() logic stays the same. Alternatively, the Comparator interface comes into play when multiple different sorting criteria are needed, allowing separate classes or lambdas to define custom compare() method logic external to the objects being sorted . This makes Comparator more flexible and reusable for multiple sorting strategies without altering the data types being sorted.
Static methods in Java interfaces provide utility functions that cannot be overridden and are accessed using the interface name rather than through an instance of a class that implements the interface . They are designed to offer static behavior pertinent to the interface's logical grouping, facilitating code reusability and avoiding instance method association . This contrasts with default methods in interfaces, which are invoked on objects and can be overridden by implementing classes to give various implementations and achieve backward compatibility.
The 'final' keyword in Java serves to limit modification and inheritance. For variables, 'final' makes them constants, prohibiting any further modification after initialization . When used with methods, 'final' prevents them from being overridden in subclass definitions . With classes, 'final' ensures that the class cannot be extended, ending inheritance at that class . This keyword ensures stability and security in code by preventing alterations that could lead to unexpected behaviors.