Xperi · Day 2 · Advanced Java
Volume II

Generics
&
Streams
& Patterns

The advanced curriculum — generics and their wildcards, the exception hierarchy, Java 8 streams and lambdas, the design patterns Xperi adores, multithreading, and the final rapid-fire revision.

Begin Reading
Easy
Medium
Hard
Xperi Asked
— Index —

The Table of Contents

Day 2 · 6 Chapters
XIII Chapter XIII · 5 Questions

Generics — Type Safety & Wildcards

The cornerstone of modern Java. Generics, type erasure, bounded types, and the PECS rule — questions that distinguish the prepared from the fortunate.

Xperi · Day 2

Generics kya hain? Java mein kyun introduce kiye gaye?

Generics Java 5 mein aaye — yeh compile-time type safety provide karte hain. Bina generics ke aap Object type ka collection bana sakte the, par runtime pe ClassCastException aata tha.

Java
// BEFORE Generics (Java 1.4)
List list = new ArrayList();
list.add("hello");
Integer n = (Integer) list.get(0);  // ClassCastException at runtime

// AFTER Generics (Java 5+)
List<String> list = new ArrayList<>();
list.add("hello");
Integer n = (Integer) list.get(0);  // COMPILE ERROR — type safety
Generics compile-time pe kaam karte hain, runtime pe sab raw types mein convert ho jaate hain — ise Type Erasure kehte hain.

Type Erasure kya hai? Internally kaise kaam karta hai?

Type Erasure ek process hai jismein compiler generic type information ko hata deta hai aur raw types / bridges mein convert kar deta hai. JVM ko generics ka pata hi nahi hota — yeh sirf compiler-level feature hai.

Java
// Source code
List<String> strings = new ArrayList<String>();
strings.add("hi");
String s = strings.get(0);

// After type erasure (what JVM sees)
List strings = new ArrayList();
strings.add("hi");
String s = (String) strings.get(0);  // compiler inserts cast
Isliye new T(), new T[], instanceof T generic types ke saath allowed NAHI hain — kyunki runtime pe T ka existence nahi hota.

Bounded Type Parameters kya hote hain? <? extends T> vs <? super T> mein kya difference hai?

PECS Rule — Producer Extends, Consumer Super.

WildcardMeaningUse when
<? extends T>Upper bound — T ya uska subtypeSirf read kar rahe ho (Producer)
<? super T>Lower bound — T ya uska supertypeSirf write kar rahe ho (Consumer)
<?>Unbounded — kuch bhiRead + write dono nahi, sirf null daal sakte ho
Java
// PECS example
public static void process(List<? extends Number> producer) { // PRODUCER — read only
    for (Number n : producer) System.out.println(n);
}

public static void fill(List<? super Integer> consumer) { // CONSUMER — write only
    consumer.add(10);
    consumer.add(20);
}
extends = "mere paas sirf produce karke dene wale hain" (read), super = "mere paas dal ke khaane wale hain" (write).

Generics mein T, E, K, V, ? ka convention kya hai?

SymbolStands forUsed in
EElementCollections — List<E>, Set<E>
KKeyMaps — Map<K, V>
VValueMaps — Map<K, V>
NNumberNumeric types
TTypeGeneric classes/methods
S, U, V2nd, 3rd, 4th TypeMulti-type parameters
?Wildcard (unknown)Read-only contexts
Yeh sirf conventions hain — compiler koi bhi naam accept karta hai. Par follow karna best practice hai.

Generics ke saath arrays kyun nahi bana sakte? new T[10] kyun illegal hai?

Type erasure ke kaaran runtime pe generic type ka existence nahi hota. Arrays ke saath problem yeh hai ki arrays reified hain (runtime pe type check karte hain), jabki generics erased hain.

Java
List<String>[] stringLists = new ArrayList<String>[10];  // COMPILE ERROR

// Workaround: raw type ya wildcard use karo
List[] stringLists = new ArrayList[10];          // OK but unchecked warning
List<?>[] stringLists = new ArrayList<?>[10];    // OK
Practical alternative: List<Object> ya List<?> use karo jab multiple types store karne ho.
XIV Chapter XIV · 5 Questions

Exception Handling — Hierarchy & Best Practices

The exception hierarchy, checked versus unchecked, try-with-resources — the foundations of production-grade Java.

Xperi · Day 2

Exception hierarchy explain karo. Checked aur Unchecked mein kya difference hai?

Java mein sab kuch Throwable se inherit hota hai, jismein 2 branches hain:

Java
Throwable
  ├── Error           (unchecked, JVM level — OutOfMemoryError, StackOverflowError)
  └── Exception
        ├── IOException           (checked — file, network failures)
        ├── SQLException          (checked)
        ├── ClassNotFoundException (checked)
        └── RuntimeException     (unchecked)
              ├── NullPointerException
              ├── ArrayIndexOutOfBoundsException
              ├── ArithmeticException
              └── IllegalArgumentException
AspectCheckedUnchecked
ExtendsException (not RuntimeException)RuntimeException
Compile checkYES — handle or declareNO — optional
CauseExternal resources (file, DB, network)Programming bugs (NPE, bad index)
RecoveryExpected, can recoverUsually fatal logic errors

try-catch-finally mein execution flow kaise kaam karta hai?

Flow rules:

  1. try block execute hota hai
  2. Agar exception aaye → matching catch block run hota hai
  3. finally block HAMESHA execute hota hai — exception aaye ya na aaye (except System.exit() ya JVM crash)
  4. Java 7 ke baad try-with-resources aaya — AutoCloseable resources automatically close hote hain
Java
// Old way
FileReader fr = null;
try {
    fr = new FileReader("file.txt");
    // read file
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fr != null) try { fr.close(); } catch (IOException e) {}
}

// NEW way (Java 7+) — cleaner
try (FileReader fr = new FileReader("file.txt")) {
    // read file — fr auto-closed
} catch (IOException e) {
    e.printStackTrace();
}
Hamesha try-with-resources use karo resources ke saath. Java 9 mein aap existing final variable bhi try-with mein use kar sakte ho.

throw vs throws mein kya difference hai?

Aspectthrowthrows
TypeKeyword used to actually throw an exceptionKeyword used in method signature to declare
UsageInside method bodyMethod signature mein
CountSingle exception object throw karta haiMultiple exception types declare kar sakta hai
Examplethrow new IOException();void read() throws IOException
Java
public void withdraw(double amount) throws InsufficientFundsException {  // DECLARE
    if (amount > balance)
        throw new InsufficientFundsException("Not enough money");  // ACTUALLY THROW
    balance -= amount;
}

Custom Exception kab banate hain? Kaise banate hain?

Jab business logic mein specific error represent karna ho. Best practice: checked extend karo agar caller ko recover karna hai, unchecked agar programming bug hai.

Java
// Checked — caller ko handle karna chahiye
public class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String msg) { super(msg); }
}

// Unchecked — programming error
public class InvalidAgeException extends RuntimeException {
    public InvalidAgeException(String msg) { super(msg); }
}
Exception ka naam end mein Exception lagao aur past tense mein describe karo — UserNotFoundException, InvalidInputException.

Java 7 ke baad multi-catch aur try-with-resources mein multiple exceptions kaise handle karte hain?

Java
// Multi-catch (Java 7+)
try {
    Class.<String>forName("com.foo.Bar").newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
    logger.error("Failed to load class", e);
}

// Multi-resource try-with-resources
try (FileReader fr = new FileReader("in.txt");
     FileWriter fw = new FileWriter("out.txt")) {
    fw.write(fr.readAllBytes());
}  // both auto-closed in REVERSE order
Resources reverse order mein close hote hain (LIFO). AutoCloseable implement karna padta hai.
XV Chapter XV · 5 Questions

Java 8 Streams & Lambdas

Functional programming in Java — guaranteed in every coding round.

Xperi · Day 2

Stream kya hota hai? Collection se kaise alag hai?

Stream ek sequence of elements hai jo functional operations support karta hai. Yeh data structure nahi hai — yeh sirf data pe operations perform karne ka tarika hai.

AspectCollectionStream
PurposeData store karnaData pe computation karna
ModificationAdd/remove elementsImmutable — original change nahi hota
IterationExternal (for/while)Internal (stream khud iterate karta hai)
LazyNoYes — terminal op tak kuch nahi hota
ReusableYesNo — ek baar consume hoke khatam

Stream pipeline ke 3 parts kya hain? Intermediate vs Terminal operations?

Stream pipeline ke 3 steps hote hain:

  1. Sourcelist.stream(), Stream.of(...), Arrays.stream(...)
  2. Intermediate operationsfilter(), map(), sorted(), distinct() — lazy, naya stream return karte hain
  3. Terminal operationcollect(), forEach(), count(), reduce() — result produce karta hai, stream khatam
Java
List<String> names = Arrays.asList("Alice", "Bob", "Anna", "Charlie");

List<String> result = names.stream()              // 1. Source
    .filter(n -> n.startsWith("A"))           // 2a. Intermediate (lazy)
    .map(String::toUpperCase)                  // 2b. Intermediate (lazy)
    .sorted()                                     // 2c. Intermediate (lazy)
    .collect(Collectors.toList());          // 3. Terminal (triggers execution)
// Result: [ALICE, ANNA]
Method reference :: lambda ka shorthand hai. String::toUpperCases -> s.toUpperCase()

map() vs flatMap() mein kya difference hai?

map() — har element ko 1:1 transform karta hai.

flatMap() — har element ko multiple elements mein "flatten" karta hai (1:N transformation).

Java
List<List<Integer>> nested = Arrays.asList(
    Arrays.asList(1, 2),
    Arrays.asList(3, 4, 5),
    Arrays.asList(6)
);

// map() — flat nahi karta
List<Stream<Integer>> mapped = nested.stream().map(l -> l.stream()).collect(Collectors.toList());

// flatMap() — flatten karta hai
List<Integer> flat = nested.stream()
    .flatMap(Collection::stream)
    .collect(Collectors.toList());
// Result: [1, 2, 3, 4, 5, 6]
map = "wrap", flatMap = "unwrap and concat". Optional ke saath flatMap bahut powerful hai.

Lambda expression kya hai? Functional interface se kya relation hai?

Lambda = anonymous function. Yeh Functional Interface (single abstract method wala) ka concise implementation hai.

Java
// Anonymous class — old, verbose
Runnable r1 = new Runnable() {
    public void run() { System.out.println("old"); }
};

// Lambda — new, concise
Runnable r2 = () -> System.out.println("new");

// With parameters
Comparator<Integer> cmp = (a, b) -> a.compareTo(b);

// Multi-line body
Function<Integer, Integer> square = x -> {
    return x * x;
};
Common Functional Interfaces: Predicate<T> (T→boolean), Function<T,R> (T→R), Consumer<T> (T→void), Supplier<T> (()→T).

Optional class kya hai? NullPointerException se kaise bachata hai?

Optional<T> ek container hai jo hold kar sakta hai ya nahi bhi kar sakta. Yeh null references ke alternative ke roop mein aaya Java 8 mein.

Java
// Old way — null check required
String name = user.getName();
if (name != null) System.out.println(name.toUpperCase());

// New way — Optional
Optional<String> opt = user.getNameOptional();
String result = opt
    .map(String::toUpperCase)
    .orElse("DEFAULT");   // safe default

// Common methods
opt.isPresent()        // true if has value
opt.ifPresent(System.out::println)  // run lambda only if present
opt.orElseThrow(() -> new NotFoundException("missing"))  // throw if empty
Optional ko field ya constructor parameter ki tarah mat use karo — sirf return types ke liye. Serialization mein bhi avoid karo.
XVI Chapter XVI · 5 Questions

Design Patterns — Xperi Favourites

Singleton, Observer, Factory, Builder, Strategy — every interview expects 2-3 of these written from memory.

Xperi · Day 2

Singleton pattern kya hai? Thread-safe kaise banate hain?

Singleton ensures ek class ka sirf ek instance ho. Use case: DB connection pool, Logger, Config manager.

Java
// 1. Eager initialization (simple but wastes memory)
public class EagerSingleton {
    private static final EagerSingleton INSTANCE = new EagerSingleton();
    private EagerSingleton() {}
    public static EagerSingleton getInstance() { return INSTANCE; }
}

// 2. Bill Pugh Singleton (BEST — lazy + thread-safe, no synchronization)
public class BillPughSingleton {
    private BillPughSingleton() {}
    private static class Helper {
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }
    public static BillPughSingleton getInstance() { return Helper.INSTANCE; }
}

// 3. Enum Singleton (best against reflection + serialization)
public enum EnumSingleton {
    INSTANCE;
    public void doWork() { /* ... */ }
}
Singleton = ek rani, ek rajya. Enum = "Joshua Bloch approved" way to break reflection attacks.

Factory pattern kya hai? Kab use karte hain?

Factory pattern object creation ko encapsulate karta hai. Client ko sirf interface pata hota hai, actual class nahi.

Java
interface Shape { void draw(); }
class Circle implements Shape { public void draw() { System.out.println("○"); } }
class Square implements Shape { public void draw() { System.out.println("□"); } }

public class ShapeFactory {
    public static Shape create(String type) {
        return switch (type) {
            case "circle" -> new Circle();
            case "square" -> new Square();
            default -> throw new IllegalArgumentException("Unknown: " + type);
        };
    }
}

// Client code
Shape s = ShapeFactory.create("circle");  // no new keyword!
s.draw();
Jab exact class runtime pe decide hoti hai based on config/input. Spring framework pura factory pe based hai.

Builder pattern kya hai? Likh ke dikhao.

Jab class mein bahut zyada optional fields hon aur telescoping constructors ugly ho jaayein, tab Builder use karo.

Java
public class User {
    private final String name;        // required
    private final String email;       // required
    private final int age;            // optional
    private final String phone;       // optional
    private final String address;     // optional

    private User(Builder b) {
        this.name = b.name;
        this.email = b.email;
        this.age = b.age;
        this.phone = b.phone;
        this.address = b.address;
    }

    public static class Builder {
        private final String name, email;
        private int age;
        private String phone, address;
        public Builder(String name, String email) { this.name = name; this.email = email; }
        public Builder age(int v) { this.age = v; return this; }
        public Builder phone(String v) { this.phone = v; return this; }
        public Builder address(String v) { this.address = v; return this; }
        public User build() { return new User(this); }
    }
}

// Usage
User u = new User.Builder("Pritam", "p@x.com").age(25).phone("999").build();
Java 16+ mein Records ne simpler cases mein builder ki zaroorat kam kar di. Par complex objects ke liye builder abhi bhi king hai.

Observer pattern kya hai? Real-world example do.

Observer = publish-subscribe. Jab ek object (Subject) ki state change ho, sab registered listeners (Observers) automatically notify ho jaate hain.

Java
interface Observer { void update(String msg); }
class Subject {
    private final List<Observer> observers = new ArrayList<>();
    public void subscribe(Observer o) { observers.add(o); }
    public void notifyAll(String msg) {
        observers.forEach(o -> o.update(msg));
    }
}

// Real-world: YouTube channel
Subject channel = new Subject();
channel.subscribe(msg -> System.out.println("Email: " + msg));
channel.subscribe(msg -> System.out.println("Push: " + msg));
channel.notifyAll("New video uploaded!");  // both notified
Java mein built-in support: java.util.Observer (deprecated), PropertyChangeListener, aur Reactive Streams (RxJava, Project Reactor).

Strategy pattern kya hai? Code example ke saath explain karo.

Strategy pattern ek family of algorithms ko define karta hai, unhe encapsulate karta hai, aur runtime pe interchange karne deta hai.

Java
interface PaymentStrategy { void pay(int amount); }
class CreditCard implements PaymentStrategy {
    public void pay(int amount) { System.out.println("Paid " + amount + " via CC"); }
}
class UPI implements PaymentStrategy {
    public void pay(int amount) { System.out.println("Paid " + amount + " via UPI"); }
}

class ShoppingCart {
    private PaymentStrategy strategy;
    public void setStrategy(PaymentStrategy s) { this.strategy = s; }
    public void checkout(int amount) { strategy.pay(amount); }
}

// Runtime pe strategy change
ShoppingCart cart = new ShoppingCart();
cart.setStrategy(new CreditCard()); cart.checkout(500);
cart.setStrategy(new UPI());        cart.checkout(500);
Strategy = "kaunsa kaam karne ka tarika" ko runtime pe select karna. Lambda se aur bhi concise ho gaya.
XVII Chapter XVII · 5 Questions

Multithreading — The OOP Context

Thread lifecycle, synchronization, deadlock prevention, volatile — must-know for production systems.

Xperi · Day 2

Thread aur Process mein kya difference hai?

AspectProcessThread
DefinitionIndependent program in executionLightweight sub-unit of a process
MemorySeparate memory spaceShared memory with other threads
CommunicationIPC (pipes, sockets) — slowDirect shared variables — fast
Creation costHighLow
Crash impactIsolatedCan crash whole process

Thread create karne ke 2 tarike kya hain?

Java
// 1. Extend Thread class
class MyThread extends Thread {
    public void run() { System.out.println("Thread running"); }
}
new MyThread().start();

// 2. Implement Runnable (PREFERRED — Java doesn't support multiple inheritance)
Runnable r = () -> System.out.println("Runnable running");
new Thread(r).start();

// Modern: ExecutorService (BEST for production)
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> System.out.println("From pool"));
pool.shutdown();
Direct Thread avoid karo — ExecutorService use karo. Thread pool automatically manage hota hai, resource leaks se bachata hai.

synchronized aur volatile mein kya difference hai?

Aspectsynchronizedvolatile
PurposeMutual exclusion (atomicity)Visibility guarantee
ScopeMethod ya blockOnly variable
PerformanceSlower (lock acquire/release)Lightweight
Compound opsSafe (e.g. i++)NOT safe for compound ops
ReentrancyYes (same thread can re-enter)N/A
Java
private volatile boolean running = true;  // visible to all threads

public void run() {
    while (running) { /* work */ }
}

public void stop() { running = false; }  // all threads see this

Deadlock kya hai? Kaise avoid karte hain?

Deadlock = 2 ya zyada threads ek doosre ke lock release karne ka wait kar rahe hain. App hang ho jaata hai.

4 Coffman Conditions (sab true honi chahiye):

  1. Mutual Exclusion — resource sirf ek thread use kare
  2. Hold and Wait — thread ek lock hold karke doosre ka wait kare
  3. No Preemption — lock forcibly nahi chheenna ja sakta
  4. Circular Wait — A waits for B, B waits for A
Avoidance strategies: Locks hamesha same order mein acquire karo, tryLock with timeout use karo, ya higher-level java.util.concurrent utilities (Semaphore, ReentrantLock) use karo.

wait() aur sleep() mein kya difference hai?

Aspectwait()sleep()
ClassObjectThread
Lock release?YesNo
Wake upnotify() / notifyAll()After timeout
Where calledInside synchronized blockAnywhere
Use caseInter-thread communicationPausing execution
Modern Java mein wait/notify avoid karo. java.util.concurrent package ka use karo: BlockingQueue, CountDownLatch, CyclicBarrier, CompletableFuture.
XVIII Chapter XVIII · 5 Questions

Final Rapid Fire — Day 2 Summary

Five quick-fire questions to test your readiness — answers crisp, examples precise.

Xperi · Day 2

== vs .equals() — kab kya use karein?

== compares references (memory address) for objects, values for primitives. .equals() compares logical content (override karna padta hai).

Java
String a = new String("hi");
String b = new String("hi");
a == b        // false (different objects)
a.equals(b)  // true  (same content)

String, StringBuilder, StringBuffer — kab kaunsa?

ClassMutableThread-safeUse when
StringNo (immutable)YesConstant text, no change
StringBuilderYesNoSingle-thread string manipulation (FASTEST)
StringBufferYesYes (synchronized)Multi-thread string manipulation

HashMap ka default initial capacity aur load factor kya hai?

Default capacity = 16, Default load factor = 0.75. Rehash hota hai jab size > 16 × 0.75 = 12 ho jaaye.

Best practice: Capacity pre-compute karo — new HashMap<>(expectedSize / 0.75 + 1) — rehash se bachne ke liye.

ArrayList vs Array — 3 key differences?

AspectArrayArrayList
SizeFixed at creationDynamic (auto-grow)
TypePrimitives + objectsObjects only (boxed primitives)
FeaturesNone extraadd, remove, contains, iterator

Immutability kaise achieve karte hain? Steps batao.

Immutability = object ki state creation ke baad change nahi hoti. Steps:

  1. Class ko final declare karo (subclassing nahi hogi)
  2. Saare fields private final banao
  3. Setter methods mat do (no mutators)
  4. Defensive copy in constructor for mutable fields
  5. Defensive copy in getters (return clone)
Java
public final class ImmutablePoint {
    private final int x, y;
    public ImmutablePoint(int x, int y) { this.x = x; this.y = y; }
    public int getX() { return x; }
    public int getY() { return y; }
}