Loading...
Loading...
Q1. Java mein OOP ke 4 pillars kya hain?
1. Encapsulation — Data hiding, private fields + public getters/setters
2. Inheritance — Child class inherits from parent (extends)
3. Polymorphism — Many forms (method overloading + overriding)
4. Abstraction — Hide implementation, show interface
Q2. Method Overloading vs Method Overriding?
// Overloading — Same name, different parameters (COMPILE-TIME polymorphism)
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // Different params
int add(int a, int b, int c) { return a + b + c; } // Different count
}
// Overriding — Child changes parent method (RUNTIME polymorphism)
class Animal {
void sound() { System.out.println("Generic sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Woof!"); } // Same signature
}
Q3. Abstract class vs Interface?
| Feature | Abstract Class | Interface | |---|---|---| | Methods | Abstract + concrete | All abstract (Java 7) / Default allowed (Java 8+) | | Variables | Any type | Only public static final | | Constructor | ✅ Can have | ❌ Cannot | | Multiple inheritance | ❌ No | ✅ Yes (implements A, B) | | Access modifier | Any | Public (default) | | When to use | Base class with shared state | Contract/API definition |
Q4. Constructor kya hai, types?
class Student {
String name;
int age;
// Default constructor (no params)
Student() {
this.name = "Unknown";
this.age = 0;
}
// Parameterized constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
Student(Student other) {
this.name = other.name;
this.age = other.age;
}
}
// Note: If you define any constructor, default is NOT auto-generated
Q5. this vs super keyword?
class Parent {
int x;
Parent(int x) { this.x = x; }
void show() { System.out.println("Parent x = " + x); }
}
class Child extends Parent {
int x;
Child(int px, int cx) {
super(px); // Call parent constructor (must be first line)
this.x = cx; // this.x = child's x
}
void show() {
super.show(); // Call parent method
System.out.println("Child x = " + this.x);
}
}
Q6. Static vs Instance members?
class Counter {
static int count = 0; // Shared across all objects
int id; // Per object
Counter() {
count++; // Increment shared count
this.id = count; // Unique per object
}
static void showCount() { // Static method
System.out.println("Total: " + count);
// System.out.println(id); ❌ Can't access instance var
}
}
Q7. final keyword kya karta hai?
final int PI = 3; // ❌ Can't reassign (constant)
final class String { } // ❌ Can't extend (no subclass)
class Parent {
final void method() { } // ❌ Can't override
}
Q8. String, StringBuilder, StringBuffer mein kya fark hai?
// String — Immutable! Every concat creates new object
String s = "Hello";
s = s + " World"; // New object created! Old "Hello" → GC
// StringBuilder — Mutable, NOT thread-safe, faster
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.insert(5, ",");
sb.delete(5, 6);
String result = sb.toString();
// StringBuffer — Mutable, thread-safe, slightly slower (synchronized)
StringBuffer sbuf = new StringBuffer("Hello");
sbuf.append(" World");
Q9. == vs .equals() for String?
String s1 = "hello";
String s2 = "hello"; // String pool — same reference
String s3 = new String("hello"); // New object in heap
s1 == s2 // true (same pool reference)
s1 == s3 // false (different objects!)
s1.equals(s3) // true (same content)
// Always use .equals() for String comparison!
Q10. Common String methods?
String s = " Hello World ";
s.trim() // "Hello World"
s.toLowerCase() // " hello world "
s.toUpperCase() // " HELLO WORLD "
s.substring(7, 12) // "World" (7 inclusive, 12 exclusive)
s.charAt(7) // 'W'
s.indexOf("World") // 8
s.contains("Hello") // true
s.replace("World", "Java") // " Hello Java "
s.split(" ") // ["", "", "Hello", "World", "", ""]
String.valueOf(42) // "42"
Integer.parseInt("42") // 42
"hello".toCharArray() // ['h','e','l','l','o']
Q11. Collections Framework hierarchy?
Iterable
└── Collection
├── List (ordered, duplicates allowed)
│ ├── ArrayList (dynamic array, O(1) access)
│ ├── LinkedList (doubly linked, O(1) insert/delete)
│ └── Vector (thread-safe ArrayList, legacy)
├── Set (no duplicates)
│ ├── HashSet (unordered, O(1))
│ ├── LinkedHashSet (insertion order)
│ └── TreeSet (sorted, O(log n))
└── Queue
├── PriorityQueue (heap-based, min by default)
├── LinkedList (also Queue)
└── Deque (ArrayDeque)
Map (key-value, separate hierarchy)
├── HashMap (unordered, O(1))
├── LinkedHashMap (insertion order)
├── TreeMap (sorted by key)
└── Hashtable (thread-safe, legacy)
Q12. ArrayList vs LinkedList?
| Operation | ArrayList | LinkedList | |---|---|---| | Access by index | O(1) | O(n) | | Insert at end | O(1) amortized | O(1) | | Insert at middle | O(n) | O(1) if iterator | | Memory | Contiguous | Extra node overhead | | Use when | Frequent access | Frequent insertions/deletions |
Q13. HashMap internal working?
HashMap<String, Integer> map = new HashMap<>();
map.put("Rahul", 90);
// 1. Compute hash: "Rahul".hashCode() → index
// 2. Store in bucket array (Entry[] table)
// 3. Collision: chaining (linked list at same index)
// Java 8+: treeify when bucket size > 8 (O(log n))
map.get("Rahul");
// 1. Compute hash → find bucket
// 2. Compare keys with .equals()
// 3. Return value
// Important:
// Initial capacity = 16, Load factor = 0.75
// When size > 16*0.75 = 12 → resize (double + rehash)
Q14. HashSet vs TreeSet vs LinkedHashSet?
// HashSet — O(1), no order
Set<Integer> hs = new HashSet<>(Arrays.asList(3,1,4,1,5,9,2));
// [1, 2, 3, 4, 5, 9] — no duplicates, unordered
// TreeSet — O(log n), sorted
Set<Integer> ts = new TreeSet<>(Arrays.asList(3,1,4,1,5,9,2));
// [1, 2, 3, 4, 5, 9] — sorted ascending
// LinkedHashSet — O(1), insertion order preserved
Set<Integer> lhs = new LinkedHashSet<>(Arrays.asList(3,1,4,1,5,9));
// [3, 1, 4, 5, 9] — insertion order, no duplicates
Q15. Checked vs Unchecked Exceptions?
// Checked — Must handle (try-catch or throws declaration)
// Compiler enforces it
public void readFile() throws IOException {
FileReader fr = new FileReader("file.txt"); // throws IOException
}
// Unchecked (RuntimeException) — Optional handling
int[] arr = new int[5];
arr[10] = 1; // ArrayIndexOutOfBoundsException
String s = null;
s.length(); // NullPointerException
int x = 5/0; // ArithmeticException
Q16. Try-Catch-Finally structure?
try {
// Code that might throw
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Generic: " + e);
} finally {
// Always runs (even if exception, even if return!)
System.out.println("Cleanup code here");
}
// Try-with-resources (auto-close)
try (FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// fr and br auto-closed even if exception occurs
Q17. Lambda Expressions?
// Before Java 8 (Anonymous class)
Runnable r = new Runnable() {
public void run() { System.out.println("Running"); }
};
// Java 8 Lambda
Runnable r = () -> System.out.println("Running");
// With parameters
Comparator<String> comp = (s1, s2) -> s1.length() - s2.length();
// Multi-line
Function<Integer, Integer> square = n -> {
int result = n * n;
return result;
};
Q18. Stream API?
List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
// Filter → Map → Collect
List<Integer> result = nums.stream()
.filter(n -> n % 2 == 0) // [2,4,6,8,10]
.map(n -> n * n) // [4,16,36,64,100]
.collect(Collectors.toList()); // Back to list
// Reduce
int sum = nums.stream().reduce(0, Integer::sum);
// Count, min, max
long count = nums.stream().filter(n -> n > 5).count();
Optional<Integer> max = nums.stream().max(Integer::compareTo);
// Collect to Map
Map<Boolean, List<Integer>> partitioned = nums.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
// String join
String joined = Stream.of("a","b","c")
.collect(Collectors.joining(", ", "[", "]")); // "[a, b, c]"
Q19. Optional class?
// Avoid NullPointerException
Optional<String> name = Optional.of("Rahul");
Optional<String> empty = Optional.empty();
Optional<String> nullable = Optional.ofNullable(null);
name.isPresent() // true
name.get() // "Rahul"
name.orElse("Unknown") // "Rahul"
empty.orElse("Unknown") // "Unknown"
name.map(String::toUpperCase) // Optional["RAHUL"]
name.ifPresent(System.out::println) // prints "Rahul"
Q20. Thread lifecycle?
New → Runnable → Running → Blocked/Waiting/Timed-Waiting → Terminated
Q21. Creating threads?
// Method 1: Extend Thread
class MyThread extends Thread {
public void run() {
System.out.println("Thread: " + Thread.currentThread().getName());
}
}
new MyThread().start(); // .start() creates new thread; .run() would be in current thread
// Method 2: Implement Runnable (preferred — allows extending other class)
class Task implements Runnable {
public void run() { System.out.println("Task running"); }
}
new Thread(new Task()).start();
// Method 3: Lambda (Java 8)
Thread t = new Thread(() -> System.out.println("Lambda thread"));
t.start();
// ExecutorService (production use)
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> System.out.println("Pool thread"));
executor.shutdown();
Q22. synchronized keyword?
class BankAccount {
private int balance = 1000;
// Synchronized method — only one thread at a time
public synchronized void withdraw(int amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount + " | Balance: " + balance);
}
}
// Synchronized block — finer-grained control
public void deposit(int amount) {
synchronized(this) {
balance += amount;
}
}
}
Core:
OOP: 10. Polymorphism kya hai, types? 11. Dynamic dispatch kya hai? 12. Covariant return type kya hai? 13. Marker interface kya hai? 14. Functional interface kya hai?
String: 15. String pool kya hai? 16. String immutable kyon hai? (Security, thread safety, caching) 17. intern() method kya karta hai?
Collections: 18. fail-fast vs fail-safe iterator? 19. Comparable vs Comparator? 20. ConcurrentHashMap vs Hashtable? 21. LinkedHashMap ka use case? 22. PriorityQueue kaise kaam karta hai? (Min-heap by default) 23. WeakHashMap kya hai?
Exception: 24. Error vs Exception? 25. throws vs throw? 26. Can we have try without catch? 27. finally mein return ho to kya hoga?
Java 8+: 28. Default methods interface mein kyon? (Backward compatibility) 29. Method reference kya hai? (Class::method) 30. Predicate, Function, Consumer, Supplier kya hain? 31. flatMap vs map? 32. parallel stream kab use karein?
Multithreading: 33. Race condition kya hai? 34. Deadlock Java mein kaise avoid karein? 35. volatile keyword kya karta hai? (Visibility guarantee) 36. wait() vs sleep()? 37. notify() vs notifyAll()? 38. ThreadLocal kya hai? 39. Callable vs Runnable? 40. Future kya hai?
Design Patterns: 41. Singleton pattern — thread-safe kaise banayein? 42. Factory pattern kya hai? 43. Builder pattern kab use karein? 44. Observer pattern?
JVM: 45. Garbage Collection kaise kaam karta hai? 46. Memory areas in JVM (Heap, Stack, Method area, PC register)? 47. Eden space, Survivor, Old gen kya hain? 48. OutOfMemoryError aur StackOverflowError mein fark? 49. finalize() method kyon deprecated hai? 50. JVM tuning flags kya hain? (-Xms, -Xmx, -XX:NewRatio)
Core Java: OOP, Collections, Exception Handling, String, Multithreading basics. Plus coding in Java on LeetCode. DSA with Java ke liye ArrayList, HashMap, PriorityQueue use karna aana chahiye.
Both accepted in most companies. Java: type-safe, verbose but clear. Python: concise, great for DSA. Choose one and master it. Java better for system design understanding.
JDK = JRE + compiler + tools (for development). JRE = JVM + libraries (to run Java). JVM = Virtual Machine (executes bytecode). Install JDK for development.
JavaScript Complete Guide — Beginner to Advanced (2026)
40 min · Beginner
ToolsGit & GitHub Complete Guide — Version Control for Students (2026)
20 min · Beginner
DatabaseSQL Complete Guide — Database Queries for B.Tech & Placements (2026)
30 min · Intermediate
PythonPython for Beginners: 15-Day Complete Learning Plan
15 min · Beginner
ReactReact Hooks Explained: useState, useEffect, useContext & More
14 min · Intermediate
DSAData Structures and Algorithms: Full Fundamentals + Interview Prep
35 min · Intermediate
Your feedback helps us improve notes and tutorials.