0% found this document useful (0 votes)
13 views28 pages

Java Interview MasterGuide

The document is a comprehensive guide for Java backend interviews, covering essential topics such as Java basics, OOP concepts, collections, exception handling, multithreading, and Java 8 features. It includes detailed explanations, real-time backend examples, and a question coverage checklist to aid in preparation. The guide is structured into sections focusing on various Java aspects, providing code-heavy insights for practical understanding.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views28 pages

Java Interview MasterGuide

The document is a comprehensive guide for Java backend interviews, covering essential topics such as Java basics, OOP concepts, collections, exception handling, multithreading, and Java 8 features. It includes detailed explanations, real-time backend examples, and a question coverage checklist to aid in preparation. The guide is structured into sections focusing on various Java aspects, providing code-heavy insights for practical understanding.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

■ JAVA BACKEND

INTERVIEW MASTER GUIDE


Core Java | OOP | Strings | Collections | Exceptions | Multithreading | Java 8

Merged & Restructured from Both PDFs • Backend-Focused • Code-Heavy

■ DOCUMENT OVERVIEW

Section 1: Java Basics (JVM · JDK · JRE · Data Types · Type Casting · Operators · Arrays · Strings · Methods · Access
Modifiers · Wrapper Classes · GC)
Section 2: OOP Concepts (Encapsulation · Inheritance · Polymorphism · Abstraction · Interfaces · Abstract Classes ·
Constructors · super/this · Inner Classes · Upcasting)
Section 3: Strings (String Pool · StringBuilder · StringBuffer · Immutability · String Methods · equals vs == · [Link])
Section 4: Collections Framework (ArrayList · LinkedList · HashMap · HashSet · TreeMap · LinkedHashMap · Queue · Deque
· Stack · Iterator · Comparable vs Comparator · Fail-Fast vs Fail-Safe)
Section 5: Exception Handling (Checked/Unchecked · try-catch-finally · throw/throws · Custom Exceptions · Common Errors)
Section 6: Multithreading (Thread · Runnable · Lifecycle · synchronized · volatile · Thread Pool)
Section 7: Java 8 Features (Lambda · Stream API · Optional · Default Methods · Functional Interfaces)
■ Question Coverage Checklist | ■ Rapid Revision Sheet
■ SECTION 1 — JAVA BASICS

1.1. What is Java? | Features of Java

Definition
Java is a high-level, object-oriented, platform-independent programming language compiled into bytecode
executed by the JVM. It follows Write Once, Run Anywhere (WORA).

Key Points
• 11 Features: Simple, Object-Oriented, Platform-Independent, Secure, Robust, Architecture-Neutral,
Portable, High-Performance, Multithreaded, Distributed, Dynamic

• JIT Compiler improves runtime performance by converting bytecode → native machine code

• Garbage Collector handles automatic memory management (no manual delete)

• Java is strictly pass-by-value (even object references are passed by value)

// Java lifecycle: .java → javac → .class (bytecode) → JVM → Output public class
OrderService { public static void main(String[] args) { [Link]("Order Service
Running on JVM"); } }

■ Real-Time Backend Example

In a Spring Boot e-commerce backend, the same .jar is deployed on Windows dev machines, Linux CI servers,
and macOS laptops without recompiling — because JVM handles OS differences.

1.2. JVM vs JRE vs JDK

Definition
JDK (Java Development Kit) = JRE + compiler (javac) + dev tools. JRE (Java Runtime Environment) = JVM + core
class libraries. JVM (Java Virtual Machine) = engine that executes bytecode.

Key Points
• JDK is needed to write and compile code; JRE is enough to run already compiled code

• JVM is NOT cross-platform; JVM implementations exist per OS — the bytecode is portable

• JVM components: Class Loader → Bytecode Verifier → Execution Engine (Interpreter + JIT) → GC

• Class Loading phases: Loading → Linking (Verify → Prepare → Resolve) → Initialization

• 3 Class Loaders: Bootstrap ([Link]) → Extension (jre/lib/ext) → Application (classpath)

• Delegation Model: child loader delegates to parent before loading class itself

// JDK = compile + run; JRE = only run // Developer machine needs JDK; Production server
only needs JRE // javac [Link] → [Link] → java PaymentService

■ Real-Time Backend Example

CI/CD pipeline: Jenkins agent needs JDK to compile microservices; production Docker containers use
JRE-only base image (eclipse-temurin:17-jre) to minimize image size.

1.3. JVM Memory Areas

Definition
JVM divides memory into distinct runtime data areas: Method Area, Heap, Java Stack, PC Registers, and
Native Method Stack.

Key Points
• Method Area: stores class metadata, static variables, static methods (shared across threads)

• Heap: stores all object instances and instance variables; managed by Garbage Collector

• Java Stack: one stack per thread; stores stack frames (local variables, operand stack, frame data)

• PC Register: holds address of current instruction being executed; one per thread

• Native Method Stack: for native (C/C++) method calls via JNI

• Stack memory is faster (LIFO); Heap is slower but larger and dynamically allocated

• StackOverflowError = stack full (deep recursion); OutOfMemoryError = heap full

// Memory allocation demo public class UserService { static int userCount = 0; // Method
Area (static) String username; // Heap (instance var) public void createUser(String name) {
// Stack frame created String id = generateId(); // Stack local variable User user = new
User(id, name); // 'user' ref on Stack; object on Heap } // Stack frame destroyed after
return }

■ Real-Time Backend Example

In high-traffic order processing, OutOfMemoryError on Heap → increase -Xmx. StackOverflowError in


recursive category tree traversal → convert to iterative with explicit Stack.

1.4. Garbage Collection

Definition
GC is JVM's automatic memory management process that identifies and removes unreachable objects from Heap
memory, preventing memory leaks without manual intervention.

Key Points
• GC algorithms: Serial GC (single-threaded, for small apps), Parallel GC (multi-threaded throughput), CMS
(low latency), G1 GC (default since Java 9, balanced), ZGC (ultra-low pause Java 11+)

• Heap generations: Young (Eden + S0 + S1) → Old (Tenured) → Metaspace (Java 8+, replaced PermGen)

• Minor GC: cleans Young generation; Major/Full GC: cleans Old generation (stop-the-world pause)

• [Link]() only suggests GC; JVM may ignore it — never rely on it for production code

• finalize() is deprecated in Java 9+; use try-with-resources or Cleaner API instead

• Tuning flags: -Xms (initial heap), -Xmx (max heap), -XX:+UseG1GC

public class SessionManager { public void clearExpiredSessions() { List<Session> sessions =


[Link](); [Link](); // Remove references → objects become
GC-eligible sessions = null; // Explicit null to aid GC (optional but clear intent) // JVM
GC will reclaim heap memory automatically } }

■ Real-Time Backend Example

Payment gateway service processes thousands of short-lived request objects per second. G1GC is configured
with -XX:MaxGCPauseMillis=200 to keep latency under SLA, while old-generation tuning prevents Full GC
pauses during peak load.

1.5. Data Types in Java

Definition
Java has two categories of data types: Primitive (8 types, stored in Stack) and Reference/Object types (stored in
Heap, references on Stack).

Key Points
• Primitives: byte(1B), short(2B), int(4B), long(8B), float(4B), double(8B), char(2B), boolean(1b)

• Default values: int=0, double=0.0, boolean=false, char='\u0000', Reference types=null

• int range: -2,147,483,648 to 2,147,483,647; long range: ±9.2 × 10^18

• Java is strictly typed — no implicit conversion from larger to smaller type without cast

• Widening (implicit): byte→short→int→long→float→double (no data loss)

• Narrowing (explicit cast): double→int loses decimal part; risk of data loss

// Type casting in payment calculation long orderAmount = 9_999_999_999L; // long for large
monetary values double taxRate = 0.18; // double for percentage double tax = orderAmount *
taxRate; // widening: long → double (implicit) int discount = (int)(orderAmount * 0.05);
// narrowing: explicit cast // Autoboxing: int → Integer (used in Collections)
List<Integer> quantities = new ArrayList<>(); [Link](100); // int autoboxed to
Integer int qty = [Link](0); // Integer unboxed to int

■ Real-Time Backend Example

Inventory system stores product quantities as int, prices as BigDecimal (never float/double for money), and
product IDs as long for future-proofing high volume. BigDecimal avoids floating-point precision errors in
financial calculations.

1.6. Operators (Arithmetic, Bitwise, Logical, Assignment)

Definition
Operators are symbols that perform operations on variables. Java supports: arithmetic, relational, logical, bitwise,
assignment, ternary, and instanceof operators.

Key Points
• Arithmetic: + - * / % ++ -- (prefix vs postfix: ++i vs i++)

• Logical: &&(short-circuit AND), ||(short-circuit OR), !(NOT)

• Bitwise: &(AND), |(OR), ^(XOR), ~(NOT), <<(left shift), >>(right shift), >>>(unsigned right shift)

• Ternary: condition ? valueIfTrue : valueIfFalse — one-liner if-else

• Bitwise left shift << n = multiply by 2^n (fast); >> n = divide by 2^n

• Bitwise operations used in permission flags, encryption, network protocols

// Permission check with bitwise operators (REST API security) int READ = 1; // 001 int
WRITE = 2; // 010 int ADMIN = 4; // 100 int userRole = READ | WRITE; // 011 = 3 (has read +
write) boolean canRead = (userRole & READ) != 0; // true boolean canAdmin = (userRole &
ADMIN) != 0; // false // Ternary for order status String status = (stock > 0) ? "IN_STOCK"
: "OUT_OF_STOCK";

■ Real-Time Backend Example

User management service uses bitwise flags for role-based access control (RBAC). A single int encodes
multiple permissions, reducing DB columns and enabling fast permission checks.

1.7. Arrays (1D, 2D, Jagged)

Definition
An array is a fixed-size, contiguous memory container of the same data type, stored in Heap. Arrays are objects in
Java and have a .length property.

Key Points
• Array size is fixed at creation — cannot be resized (use ArrayList for dynamic size)

• Default values: int[] → 0, boolean[] → false, String[] → null

• 2D array: int[][] matrix = new int[rows][cols]; — array of arrays

• Jagged array: each row can have different column count (irregular 2D array)

• [Link]() — O(n log n); [Link]() — O(log n) on sorted array

• ArrayIndexOutOfBoundsException thrown if index < 0 or index >= length

• [Link]() is faster than manual loop for copying arrays

import [Link]; // Product price matrix (category × tier) double[][] pricing = new
double[3][4]; // 3 categories, 4 tiers pricing[0][0] = 99.99; // Electronics, Tier-1 //
Jagged: orders per day per user (variable orders) int[][] ordersPerDay = new int[7][];
ordersPerDay[0] = new int[]{10, 5, 8}; // Mon: 3 users ordersPerDay[1] = new int[]{3, 12};
// Tue: 2 users // Sort product IDs and binary search int[] productIds = {105, 203, 301,
412, 500}; int idx = [Link](productIds, 301); // returns 2

■ Real-Time Backend Example

E-commerce recommendation engine stores user-product similarity scores in a 2D array for fast access.
Jagged arrays represent per-user purchase history with variable lengths, saving memory compared to a
rectangular array.

1.8. Control Flow (if-else, switch, loops, break/continue)

Definition
Control flow statements determine the order of execution: conditional (if-else, switch), loops (for, while, do-while),
and jump (break, continue, return).

Key Points
• do-while executes body at least once before checking condition (exit-controlled loop)

• while may execute 0 times if condition is false from the start (entry-controlled)

• switch works with: int, char, String (Java 7+), enum; uses fall-through unless break is present

• Enhanced for-each loop: for(Type item : collection) — read-only iteration

• break exits the nearest loop/switch; continue skips to next iteration

• Labeled break/continue: allows breaking out of nested loops

// Order status routing with switch String orderStatus = "SHIPPED"; switch (orderStatus) {
case "PLACED": notifyWarehouse(); break; case "SHIPPED": sendTrackingEmail(); break; case
"DELIVERED": closeOrder(); break; default: logUnknownStatus(); } // Process batch orders
with continue (skip cancelled) for (Order order : orders) { if ([Link]())
continue; processPayment(order); }

■ Real-Time Backend Example

Order processing pipeline uses switch-case for routing orders by status to different microservice handlers, with
continue to skip cancelled orders in batch jobs and labeled break to exit nested retry loops when max attempts
reached.
1.9. Methods — Definition, Parameters, Return Types, Varargs

Definition
A method is a reusable block of code that performs a specific task. It has: access modifier, return type, name,
parameters (optional), body, and optional throws clause.

Key Points
• Java is pass-by-value: primitive changes don't reflect outside; object field changes DO reflect

• Method overloading: same name, different parameter list (compile-time/static polymorphism)

• Varargs (variable args): void log(String... msgs) — must be last parameter, treated as array

• Static methods belong to class; instance methods belong to object

• void return type = no return value; other types must return a matching value

• Recursive methods must have a base case to avoid StackOverflowError

public class PaymentService { // Method overloading public double calculateTotal(double


price, int qty) { return price * qty; } public double calculateTotal(double price, int qty,
double discount) { return price * qty * (1 - discount); } // Varargs for logging events
public void auditLog(String action, String... details) { [Link](action + ": " +
[Link](details)); } // auditLog("PAYMENT", "orderId=123", "amount=500",
"status=OK"); }

■ Real-Time Backend Example

REST API service uses overloaded calculateShipping() methods: one for domestic (city, weight) and one for
international (country, weight, courier). Varargs used in audit log events.

1.10. Access Modifiers

Definition
Access modifiers control the visibility/accessibility of classes, methods, and variables. Java has four: private,
default (package-private), protected, public.

Key Points
Modifier Same Class Same Package Subclass Other Package

private ✓ ✗ ✗ ✗

default ✓ ✓ ✗ ✗

protected ✓ ✓ ✓ ✗

public ✓ ✓ ✓ ✓

public class UserAccount { private String password; // only accessible within UserAccount
protected String email; // accessible in subclasses String username; // default: same
package only public String userId; // accessible everywhere private String
hashPassword(String raw) { return [Link](raw); } public boolean authenticate(String
raw) { return hashPassword(raw).equals([Link]); } }

■ Real-Time Backend Example

In a user management service, password field is private with no getter (data hiding). Authentication logic is
internal. Only authenticate() is public — exposed via REST controller.

1.11. Wrapper Classes & Autoboxing/Unboxing


Definition
Wrapper classes (Integer, Double, Long, Boolean, etc.) wrap primitive types into objects, enabling use in
Collections. Autoboxing: primitive → wrapper automatically. Unboxing: wrapper → primitive automatically.

Key Points
• 8 wrappers: Byte, Short, Integer, Long, Float, Double, Character, Boolean

• [Link]("123") — String to int; [Link](123) — int to String

• Integer cache: Java caches Integer objects from -128 to 127 (== returns true in this range)

• Beware: Integer a=200; Integer b=200; a==b is FALSE (outside cache); use equals()

• Unboxing null wrapper causes NullPointerException

• Collections only work with objects (not primitives) → autoboxing is essential

// Autoboxing in product inventory Map<String, Integer> stockMap = new HashMap<>();


[Link]("SKU001", 500); // int 500 autoboxed to Integer int qty =
[Link]("SKU001"); // Integer unboxed to int // Integer cache trap Integer a = 100;
Integer b = 100; [Link](a == b); // true (cached) Integer x = 200; Integer y =
200; [Link](x == y); // false! [Link]([Link](y)); // true
(correct) // Safe parseInt with validation String priceStr = [Link]("price");
double price = [Link](priceStr); // may throw NumberFormatException

■ Real-Time Backend Example

REST API parses query params as Strings, then uses [Link]() / [Link]() for order
quantities and prices. Null-safety required: Integer instead of int in DTO to distinguish 'not provided' from 0.

1.12. static Keyword (Variable, Method, Block, Nested Class)

Definition
The static keyword means the member belongs to the class itself, not to any instance. Static members are
shared across all objects and loaded at class initialization.

Key Points
• Static variable: one copy shared by all instances; stored in Method Area

• Static method: can be called without creating an object; cannot access instance members

• Static block: runs once when class is first loaded; used for static initialization

• Static nested class: can exist without outer class instance

• Cannot use 'this' or 'super' in static context

• Utility classes (Math, Arrays, Collections) use static methods

public class DatabaseConfig { private static final String DB_URL =


"jdbc:mysql://localhost/orders"; private static int connectionCount = 0; // shared counter
static { // Runs once at class loading — load DB driver
[Link]("[Link]"); [Link]("DB Driver loaded"); }
public static Connection getConnection() throws SQLException { connectionCount++; return
[Link](DB_URL); } }

■ Real-Time Backend Example

Singleton pattern for DB connection pool uses static field and static factory method. Static block initializes the
connection pool once. Utility methods (like price formatters) are static since they don't need instance state.
■■ SECTION 2 — OOP CONCEPTS

2.1. 4 Pillars of OOP

Definition
OOP is a programming paradigm based on objects. The 4 pillars are: Encapsulation, Inheritance,
Polymorphism, Abstraction.

Key Points
• Encapsulation: binding data (fields) and methods into a class; hiding data using private + getters/setters

• Inheritance: child class acquires properties of parent class using 'extends'; promotes code reuse

• Polymorphism: one interface, multiple implementations; compile-time (overloading) and runtime (overriding)

• Abstraction: hiding implementation details; showing only essential features via abstract class or interface

• Java does NOT support multiple class inheritance (diamond problem); uses interfaces instead

// All 4 pillars in a Payment system // Abstraction: contract defined abstract class


PaymentGateway { protected String merchantId; // Encapsulation: protected abstract void
processPayment(double amount); // Abstraction public void logTransaction(String id) { //
Concrete method [Link]("TX: " + id); } } // Inheritance + Polymorphism class
StripeGateway extends PaymentGateway { @Override public void processPayment(double amount)
{ // Runtime polymorphism [Link]("Stripe charging: " + amount); } }

■ Real-Time Backend Example

Payment processing: PaymentGateway is abstract. StripeGateway, RazorpayGateway, PayPalGateway each


override processPayment(). At runtime, the correct implementation is called based on user's chosen gateway
— runtime polymorphism in action.

2.2. Class & Object | Constructor

Definition
A Class is a blueprint/template defining fields and methods. An Object is a runtime instance of a class allocated in
Heap memory. A Constructor initializes the object when it is created with 'new'.

Key Points
• Default constructor: no-arg, provided by compiler if no constructor is defined

• Parameterized constructor: accepts arguments for initialization

• Constructor chaining: this() calls same-class constructor; super() calls parent constructor

• super() must be the first statement in a child constructor

• Copy constructor: creates a new object as a copy of an existing one

• Constructors are NOT inherited; they don't have a return type

public class Order { private String orderId; private double amount; private String status;
// No-arg constructor public Order() { this("ORD-" + [Link](), 0.0); } //
Parameterized constructor public Order(String orderId, double amount) { [Link] =
orderId; [Link] = amount; [Link] = "PLACED"; } // Copy constructor public
Order(Order other) { [Link] = [Link]; [Link] = [Link]; [Link]
= [Link]; } public String getOrderId() { return orderId; } }

■ Real-Time Backend Example


Order DTO uses parameterized constructor for API request mapping. Copy constructor creates order clones
for retry logic. Builder pattern (via Lombok @Builder) commonly replaces multiple constructors in complex
domain objects.

2.3. Encapsulation & Data Hiding

Definition
Encapsulation is wrapping data (fields) and code (methods) into a single unit (class) and restricting direct access to
fields using private with controlled access via public getters/setters.

Key Points
• Achieves data hiding: internal state cannot be changed arbitrarily

• Validation logic can be placed in setters to enforce business rules

• Read-only field: provide getter but no setter

• Write-only field: provide setter but no getter (rare)

• JavaBean convention: private fields + public getters + public setters + no-arg constructor

• Lombok @Data / @Getter / @Setter auto-generates boilerplate in Spring Boot projects

public class ProductInventory { private String productId; private int stockQuantity;


private double price; // Setter with business validation public void setStockQuantity(int
qty) { if (qty < 0) throw new IllegalArgumentException("Stock cannot be negative");
[Link] = qty; } public void setPrice(double price) { if (price <= 0) throw new
IllegalArgumentException("Price must be positive"); [Link] = price; } public int
getStockQuantity() { return stockQuantity; } public double getPrice() { return price; } }

■ Real-Time Backend Example

Inventory service enforces stock can never go negative via setter validation. Price field has no direct access —
only through validated setter, preventing zero/negative prices from being persisted to the database.

2.4. Inheritance & Types | super keyword

Definition
Inheritance allows a child class to acquire properties and behaviors of a parent class using extends. super is a
reference to the parent class object used in child class.

Key Points
• Types: Single (A→B), Multilevel (A→B→C), Hierarchical (A→B, A→C), Hybrid (via interfaces)

• Multiple inheritance with classes is NOT supported in Java (diamond problem)

• [Link]() — calls parent's version; [Link] — accesses parent's field

• super() — calls parent constructor; must be first line in child constructor

• Method hiding: if parent and child both have a static method with same signature, NOT overriding

• Final class cannot be extended; final method cannot be overridden

• IS-A relationship: Dog IS-A Animal (use inheritance); HAS-A: Car HAS-A Engine (use composition)
// Multilevel inheritance in notification system class Notification { protected String
message; public Notification(String msg) { [Link] = msg; } public void send() {
[Link]("Sending: " + message); } } class EmailNotification extends Notification
{ private String recipient; public EmailNotification(String msg, String to) { super(msg);
// calls parent constructor [Link] = to; } @Override public void send() {
[Link](); // calls parent method [Link]("To: " + recipient); } }

■ Real-Time Backend Example

E-commerce notification system: Notification (base) → EmailNotification → OrderConfirmationEmail. Each


level adds specificity. super() chains constructors. Prefer composition over inheritance for complex scenarios
(has-a over is-a).

2.5. Polymorphism — Overloading vs Overriding

Definition
Compile-time polymorphism (static binding): method overloading — same name, different parameters. Runtime
polymorphism (dynamic binding): method overriding — child provides its own implementation of parent method.

Key Points
• Overloading: resolved at compile time; parameter type/number/order must differ; return type alone is NOT
enough

• Overriding: resolved at runtime; @Override annotation recommended; method signature must match exactly

• Overriding rules: can't reduce visibility; can't declare new checked exceptions; covariant return type allowed
(Java 5+)

• Covariant return type: overriding method can return subtype of parent's return type

• Virtual dispatch: JVM checks actual object type at runtime, not reference type

• Private/static/final methods CANNOT be overridden

// Overloading in OrderService class OrderService { public Order placeOrder(String


productId) { ... } // 1 arg public Order placeOrder(String productId, int qty) { ... } // 2
args public Order placeOrder(Cart cart) { ... } // Cart arg } // Runtime polymorphism in
discount calculation abstract class DiscountStrategy { abstract double apply(double price);
} class SeasonalDiscount extends DiscountStrategy { @Override double apply(double price) {
return price * 0.80; } // 20% off } class LoyaltyDiscount extends DiscountStrategy {
@Override double apply(double price) { return price * 0.90; } // 10% off } // Usage:
DiscountStrategy d = new SeasonalDiscount(); // runtime binding double finalPrice =
[Link](1000.0); // calls [Link]()

■ Real-Time Backend Example

Strategy pattern for discount engine: DiscountStrategy reference changes at runtime based on user type
(new/loyal/VIP). The correct apply() is dispatched at runtime — core example of runtime polymorphism in
backend business logic.

2.6. Abstract Class vs Interface

Definition
An Abstract Class can have both abstract and concrete methods; extended by one class. An Interface defines a
contract (pure abstraction); implemented by multiple classes; supports default/static methods since Java 8.

Key Points
Feature Abstract Class Interface
Keyword abstract interface

Extends/Implements extends (one only) implements (multiple)

Methods abstract + concrete abstract + default + static

Fields any type public static final only

Constructor Yes No

Access modifiers Any public (default)

When to use Shared code + IS-A Contract/capability

// Interface: capability contract interface Payable { void pay(double amount); // abstract


default void refund(double amount) { // default (Java 8) [Link]("Refunding " +
amount); } static boolean isValidAmount(double a) { return a > 0; } // static } // Abstract
class: shared base for all payment processors abstract class BasePaymentProcessor
implements Payable { protected String apiKey; public BasePaymentProcessor(String key) {
[Link] = key; } abstract void validateCard(); // each processor validates differently
public void logPayment(double amt) { /* shared logging logic */ } }

■ Real-Time Backend Example

Payable interface is implemented by StripeProcessor, RazorpayProcessor, PayPalProcessor.


BasePaymentProcessor (abstract) provides common API key + logging. A class can implement multiple
interfaces but extend only one abstract class.

2.7. 'this' Keyword

Definition
this is a reference variable that refers to the current object instance. It is used to distinguish instance variables
from parameters, chain constructors, and pass the current object as an argument.

Key Points
• [Link] — disambiguation when parameter name = field name

• this() — constructor chaining within the same class (must be first statement)

• return this — method chaining / Builder pattern

• Cannot use 'this' in static context

public class CartItem { private String sku; private int qty; private double price; public
CartItem(String sku, int qty, double price) { [Link] = sku; // this disambiguates
[Link] = qty; [Link] = price; } // Builder-style method chaining via 'return this'
public CartItem withDiscount(double pct) { [Link] = [Link] * (1 - pct); return
this; // enables chaining } } // Usage: new
CartItem("SKU1",2,500.0).withDiscount(0.1).withDiscount(0.05);

■ Real-Time Backend Example

Builder pattern in Order domain object uses 'return this' for fluent API: new
OrderBuilder().withProduct(p).withQty(2).withAddress(a).build().

2.8. Upcasting & Downcasting

Definition
Upcasting: assigning child object to parent reference (implicit, safe, always allowed). Downcasting: casting
parent reference back to child type (explicit, requires instanceof check).
Key Points
• Upcasting is implicit and safe: Payment p = new CreditCardPayment();

• Downcasting requires explicit cast: CreditCardPayment cc = (CreditCardPayment) p;

• ClassCastException thrown if the actual object is not of the target type

• Always use instanceof before downcasting to avoid ClassCastException

• Java 16+ pattern matching instanceof: if (p instanceof CreditCardPayment cc) { [Link](); }

Payment payment = new CreditCardPayment("4111..."); // Upcasting (implicit)


[Link](500.0); // polymorphic call // Safe downcasting with instanceof if (payment
instanceof CreditCardPayment) { CreditCardPayment cc = (CreditCardPayment) payment; //
explicit downcast [Link](); } // Java 16+ pattern matching if (payment instanceof
CreditCardPayment cc) { [Link](); // cc is already cast }

■ Real-Time Backend Example

Payment processor receives Payment reference. When reward points need to be applied, it downcasts to
CreditCardPayment after instanceof check. Java 16 pattern matching makes this more concise and safe in
modern microservices.
■ SECTION 3 — STRINGS

3.1. String Immutability & String Pool

Definition
Strings in Java are immutable — once created, their value cannot be changed. The String Pool (String Intern
Pool) is a special area in Heap (Java 7+) where JVM stores unique String literals for memory efficiency.

Key Points
• String literal: String s = "hello"; — checks pool first, reuses if exists

• new String("hello") — always creates a new object in Heap, bypasses pool

• [Link]() — moves the string to pool / returns pooled reference

• Immutability makes String thread-safe and suitable as HashMap key

• Every 'modification' (concat, replace) creates a NEW String object

• Immutability is why String's hashCode is computed once and cached

• == compares references; .equals() compares content (always use equals() for Strings)

// String pool vs heap String s1 = "order"; // Pool String s2 = "order"; // Same pool
reference String s3 = new String("order"); // New Heap object [Link](s1 == s2);
// true (same pool ref) [Link](s1 == s3); // false (different heap object)
[Link]([Link](s3)); // true (same content) // Immutability: concat creates
new object String status = "ORDER"; status = status + "_SHIPPED"; // new String created;
old 'ORDER' is GC-eligible // As HashMap key (safe because immutable + hashCode cached)
Map<String, Order> orderCache = new HashMap<>(); [Link]("ORD-001", order);

■ Real-Time Backend Example

Order IDs as String keys in a ConcurrentHashMap are safe because String is immutable — hashCode won't
change. JWT tokens are Strings; their immutability prevents accidental modification during authentication flow.

3.2. String vs StringBuilder vs StringBuffer

Definition
String: immutable, thread-safe by nature. StringBuilder: mutable, NOT thread-safe, better performance.
StringBuffer: mutable, thread-safe (synchronized methods), slower than StringBuilder.

Key Points
Feature String StringBuilder StringBuffer

Mutable No Yes Yes

Thread-safe Yes (immutable) No Yes (sync)

Performance Slow (concat) Fastest Slower than SB

Use case Constants, keys Single-thread loops Multi-thread concat


// Building CSV report — use StringBuilder (single thread) public String
generateOrderReport(List<Order> orders) { StringBuilder sb = new StringBuilder();
[Link]("OrderId,Amount,Status\n"); for (Order o : orders) {
[Link]([Link]()).append(",") .append([Link]()).append(",")
.append([Link]()).append("\n"); } return [Link](); } // Thread-safe log builder —
use StringBuffer public class AuditLogger { private StringBuffer log = new StringBuffer();
public synchronized void append(String msg) { [Link](msg); } }

■ Real-Time Backend Example

Report generation service builds multi-line CSV/JSON responses using StringBuilder (O(n) instead of O(n²)
with String+). Multi-threaded audit logger uses StringBuffer. In Java 8+, [Link]() and StringJoiner are also
preferred alternatives.

3.3. Important String Methods

Key Points — Most-Asked String Methods


• length() — number of characters

• charAt(i) — char at index i

• substring(start) / substring(start, end) — extracts part of string

• indexOf(str) / lastIndexOf(str) — first/last occurrence index

• contains(str) — boolean; startsWith(str) / endsWith(str)

• equals(str) / equalsIgnoreCase(str) — content comparison

• toLowerCase() / toUpperCase() — case conversion

• trim() — removes leading/trailing whitespace; strip() — Unicode-aware (Java 11)

• replace(old, new) / replaceAll(regex, new) — replacement

• split(regex) — returns String[]; join(delimiter, elements) — joins with delimiter

• [Link]() / formatted() — formatted string (printf-style)

• isEmpty() — length == 0; isBlank() — blank or whitespace only (Java 11)

• toCharArray() — converts to char[]

// REST API: parse and validate order payload String raw = " ORD-001,Electronics,599.99 ";
String clean = [Link](); // "ORD-001,Electronics,599.99" String[] parts =
[Link](","); // ["ORD-001","Electronics","599.99"] String orderId = parts[0]; //
"ORD-001" String category = parts[1].toLowerCase(); // "electronics" double price =
[Link](parts[2]); // 599.99 // Format for response String msg =
[Link]("Order %s placed: Rs %.2f", orderId, price); // Email validation String email
= "user@[Link]"; boolean valid = [Link]("@") && [Link](".com");

■ Real-Time Backend Example

API gateway parses CSV batch upload files using split(','), validates emails with contains, normalizes category
names with toLowerCase(), and builds formatted response messages using [Link]().
■ SECTION 4 — COLLECTIONS FRAMEWORK
Java Collections Framework (JCF) hierarchy: Iterable → Collection → List / Queue / Set. Map is separate (not a
Collection). All in [Link] package.

4.1. ArrayList vs LinkedList

Definition
ArrayList: dynamic array, O(1) random access, O(n) insertion/deletion in middle. LinkedList: doubly-linked list,
O(n) access, O(1) insertion/deletion at head/tail; also implements Deque.

Key Points
Feature ArrayList LinkedList

Internal structure Dynamic array Doubly linked list

Access by index O(1) O(n)

Insert/Delete at middle O(n) (shift elements) O(1) (pointer update)

Insert/Delete at end O(1) amortized O(1)

Memory overhead Lower Higher (node pointers)

Default capacity 10 (grows by 50%) No fixed capacity

Best for Read-heavy, random access Queue/Deque, frequent insert/delete

// ArrayList: product catalog (frequent read, index access) List<Product> catalog = new
ArrayList<>(); [Link](new Product("P001", "Laptop", 45000.0)); Product p =
[Link](0); // O(1) [Link](1); // O(n) - shifts elements // LinkedList as
Queue: order processing queue Queue<Order> orderQueue = new LinkedList<>();
[Link](new Order("ORD-001")); // add to tail O(1) Order next = [Link]();
// remove from head O(1)

■ Real-Time Backend Example

Product catalog uses ArrayList (fast index access for display/pagination). Order processing uses LinkedList as
Queue (FIFO). Shopping cart uses ArrayList (iterate + add at end). Never use LinkedList if random access is
needed.

4.2. HashMap — Internal Working | HashMap vs Hashtable

Definition
HashMap stores key-value pairs using hashing. Internally uses an array of Node<K,V> buckets. Key's hashCode()
determines bucket; equals() resolves collisions. Average O(1) get/put; worst case O(log n) with Java 8 treeification.

Key Points
• Default initial capacity: 16; load factor: 0.75 (resize at 75% full)

• Resize: capacity doubles; all entries rehashed — expensive! Pre-size if count known

• Collision resolution: chaining (linked list) → Java 8: converts to Red-Black Tree at 8+ entries per bucket

• Keys must properly implement hashCode() AND equals() — violation causes lost entries

• HashMap: not synchronized, allows one null key, multiple null values

• Hashtable: synchronized, no null key/value, legacy (use ConcurrentHashMap instead)


• LinkedHashMap: maintains insertion order; TreeMap: sorted by natural/Comparator order

• ConcurrentHashMap: thread-safe, segment-level locking, preferred over Hashtable

• Iteration order: HashMap (random), LinkedHashMap (insertion), TreeMap (sorted)

// Product lookup cache Map<String, Product> productCache = new HashMap<>(128, 0.75f); //


pre-sized [Link]("SKU-001", new Product("Laptop", 45000.0)); // getOrDefault —
safe retrieval Product p = [Link]("SKU-999", [Link]); //
computeIfAbsent — lazy load [Link]("SKU-002", k ->
[Link](k)); // Iteration over entries for ([Link]<String, Product> entry :
[Link]()) { [Link]([Link]() + " = " +
[Link]().getName()); } // Thread-safe map for concurrent request handling
Map<String, Order> activeOrders = new ConcurrentHashMap<>();

■ Real-Time Backend Example

Product cache in REST API uses HashMap for O(1) lookup by SKU. Session store uses ConcurrentHashMap
(thread-safe). Order history by date uses TreeMap (sorted by date key). LRU cache for recent products uses
LinkedHashMap with access-order=true.

4.3. HashSet vs LinkedHashSet vs TreeSet

Definition
Set implementations store unique elements only (no duplicates). HashSet: backed by HashMap, no order, O(1).
LinkedHashSet: insertion-ordered. TreeSet: sorted (natural or Comparator), O(log n).

Key Points
• HashSet internally uses HashMap: element is stored as key, dummy PRESENT object as value

• Set uses hashCode() + equals() to determine uniqueness — override both in custom objects

• TreeSet implements NavigableSet — provides floor(), ceiling(), headSet(), tailSet()

• HashSet: O(1) add/remove/contains; TreeSet: O(log n) for all operations

• LinkedHashSet: O(1) but maintains insertion order (useful for dedup while preserving order)

// HashSet: unique product categories for filter panel Set<String> categories = new
HashSet<>(); [Link](p -> [Link]([Link]())); // auto dedup //
LinkedHashSet: unique tags in insertion order Set<String> tags = new LinkedHashSet<>();
[Link]("electronics"); [Link]("mobile"); [Link]("offer"); // TreeSet: sorted coupon
codes for display Set<String> coupons = new TreeSet<>();
[Link]([Link]("SAVE30", "FLAT50", "BUY2GET1")); // Iterates: BUY2GET1,
FLAT50, SAVE30 (alphabetical) String best = ((TreeSet<String>)coupons).last(); // SAVE30

■ Real-Time Backend Example

E-commerce filter panel deduplicates product categories using HashSet. Search history uses LinkedHashSet
(preserves order, no duplicates). Coupon code list uses TreeSet for alphabetical display.

4.4. Queue, Deque & Stack

Definition
Queue: FIFO — offer/poll/peek. Deque: double-ended queue (insert/remove from both ends). Stack: LIFO —
push/pop/peek. PriorityQueue: orders by natural/Comparator order (not FIFO).

Key Points
• Queue methods: offer() (add, no exception), poll() (remove, returns null), peek() (view head)

• vs add()/remove()/element() — throw exceptions on failure


• ArrayDeque is preferred over LinkedList for Queue/Stack (faster, no nulls)

• PriorityQueue: min-heap by default; max-heap: new PriorityQueue<>([Link]())

• Stack class is legacy — use Deque/ArrayDeque instead

• BlockingQueue (LinkedBlockingQueue) for producer-consumer in multithreaded apps

// Order fulfillment queue (FIFO) Queue<Order> fulfillmentQueue = new ArrayDeque<>();


[Link](order1); Order nextOrder = [Link](); // process
oldest first // Priority Queue: process high-value orders first PriorityQueue<Order>
priorityQueue = new PriorityQueue<>(
[Link](Order::getAmount).reversed() ); [Link](new
Order("ORD1", 500.0)); [Link](new Order("ORD2", 5000.0)); Order highValue =
[Link](); // ORD2 (5000) first // Undo stack for cart modifications
Deque<CartAction> undoStack = new ArrayDeque<>(); [Link](new
AddItemAction("SKU-001")); CartAction last = [Link](); // undo last action

■ Real-Time Backend Example

Order fulfillment uses ArrayDeque as FIFO queue. Priority-based processing uses PriorityQueue (premium
customers first). Undo/redo for cart edits uses Deque as stack. Producer-consumer inventory alerts use
LinkedBlockingQueue.

4.5. Iterator | Fail-Fast vs Fail-Safe Iterators

Definition
An Iterator traverses a collection without exposing its internal structure. Fail-Fast iterators throw
ConcurrentModificationException if the collection is modified during iteration. Fail-Safe iterators work on a copy —
no exception.

Key Points
• Fail-Fast: ArrayList, HashMap, HashSet — use modCount to detect structural modification

• Fail-Safe: CopyOnWriteArrayList, ConcurrentHashMap — iterate over snapshot

• Use [Link]() to safely remove during iteration (not [Link]())

• ListIterator: bidirectional iteration for List; supports add/set during traversal

• For-each loop uses Iterator internally — same ConcurrentModificationException risk

• CopyOnWriteArrayList: safe for concurrent reads, expensive writes (creates new array)

// Fail-fast: remove expired sessions (safe via [Link]) Iterator<Session> it =


[Link](); while ([Link]()) { if ([Link]().isExpired()) [Link](); // safe
removal } // Fail-safe: CopyOnWriteArrayList for event listeners List<OrderEventListener>
listeners = new CopyOnWriteArrayList<>(); // Multiple threads can read; add/remove creates
new copy for (OrderEventListener l : listeners) { [Link](order); // safe —
iterating over snapshot }

■ Real-Time Backend Example

Session cleanup job uses [Link]() to safely remove expired sessions. Order event publisher uses
CopyOnWriteArrayList so listeners can be added/removed concurrently while notifications are being
dispatched.

4.6. Comparable vs Comparator

Definition
Comparable ([Link]): natural ordering; class itself defines sort order via compareTo(). Comparator ([Link]):
external sorting logic; can have multiple strategies; passed to sort() / PriorityQueue.

Key Points
• Comparable: implement in the class — 'this class has a natural order'

• Comparator: implement externally — 'multiple possible sort orders'

• compareTo() returns: negative (this < other), 0 (equal), positive (this > other)

• [Link]() / thenComparing() / reversed() — Java 8 chained comparators

• [Link](list) uses Comparable; [Link](list, comparator) uses Comparator

• TreeMap/TreeSet use Comparable by default; can accept Comparator in constructor

// Comparable: Order has natural order by date public class Order implements
Comparable<Order> { private LocalDate orderDate; private double amount; @Override public
int compareTo(Order other) { return [Link]([Link]); // natural:
by date } } // Comparator: multiple sort strategies Comparator<Order> byAmount =
[Link](Order::getAmount); Comparator<Order> byAmountThenDate =
byAmount .thenComparing(Order::getOrderDate).reversed(); List<Order> orders =
[Link](); [Link](byAmountThenDate); // sort by amount desc, then date desc

■ Real-Time Backend Example

Order history default sort uses Comparable (by date). Admin dashboard uses Comparator chains to sort by
amount, status, or customer tier. PriorityQueue for SLA-based ticket processing uses Comparator on deadline
field.
■■ SECTION 5 — EXCEPTION HANDLING

5.1. Exception Hierarchy | Checked vs Unchecked

Definition
Java uses a Throwable hierarchy: Error (JVM-level, not recoverable) and Exception (program-level). Exceptions
are either Checked (compile-time — must be handled/declared) or Unchecked (RuntimeException — optional).

Key Points
• Hierarchy: Throwable → Error (OutOfMemoryError, StackOverflowError) / Exception

• Exception → Checked (IOException, SQLException) / RuntimeException (Unchecked)

• Checked: must use try-catch or declare with throws; enforced at compile time

• Unchecked: subclass of RuntimeException; optional to handle (NullPointerException,


ArrayIndexOutOfBoundsException, ClassCastException, NumberFormatException,
IllegalArgumentException)

• Common interview errors: NoSuchMethodError, NoClassDefFoundError, StackOverflowError,


OutOfMemoryError, ExceptionInInitializerError, UnsupportedClassVersionError

• Error classes: not intended to be caught; indicate JVM/environment issues

// Checked exception: must handle (DB might be down) public Order findOrder(String id)
throws SQLException { Connection conn = [Link](DB_URL); // ... query
... } // Unchecked exceptions in payment validation public void processPayment(String
amountStr, String orderId) { if (orderId == null) throw new NullPointerException("orderId
null"); double amount = [Link](amountStr); // NumberFormatException
(unchecked) if (amount <= 0) throw new IllegalArgumentException("Invalid amount"); }

■ Real-Time Backend Example

Payment service: SQLException (checked) when DB is unavailable must be caught and rethrown as a
ServiceException. NullPointerException (unchecked) for null order IDs is prevented by @NonNull validation at
controller level.

5.2. try-catch-finally | try-with-resources | multi-catch

Definition
try: risky code block. catch: handles specific exception. finally: always executes (even if exception or return).
try-with-resources (Java 7+): auto-closes AutoCloseable resources.

Key Points
• finally executes always — except [Link]() or JVM crash

• finally can override return value of try block (antipattern — avoid return in finally)

• Multi-catch: catch (IOException | SQLException e) — common handler for multiple types

• try-with-resources: resources auto-closed in reverse declaration order

• Exception chaining: new RuntimeException("msg", originalException) — preserves root cause

• Re-throwing: catch, log, then rethrow the same or a wrapped exception


// try-with-resources: auto-close DB connection public List<Order> fetchOrders(String
userId) throws ServiceException { try (Connection conn = [Link]();
PreparedStatement ps = [Link]( "SELECT * FROM orders WHERE user_id=?")) {
[Link](1, userId); ResultSet rs = [Link](); return mapToOrders(rs); } catch
(SQLException e) { throw new ServiceException("DB error fetching orders", e); // chaining }
// conn and ps auto-closed in finally } // Multi-catch for inventory update try {
[Link](sku, qty); } catch (ItemNotFoundException | OutOfStockException e)
{ return [Link]().body([Link]()); } finally {
[Link]("INVENTORY_UPDATE", sku); }

■ Real-Time Backend Example

DB access layer uses try-with-resources to guarantee connection closure even on exception. REST controllers
use multi-catch to return 400 for multiple business exceptions. Finally block records audit trail regardless of
success/failure.

5.3. throw vs throws | Custom Exceptions

Definition
throw: used inside a method to explicitly throw an exception object. throws: used in method signature to declare
checked exceptions it may throw. Custom Exception: user-defined exception extending Exception or
RuntimeException.

Key Points
• throw creates and throws an exception: throw new OrderNotFoundException(id);

• throws declares: public void placeOrder() throws InsufficientStockException

• Custom checked exception: extends Exception (caller must handle)

• Custom unchecked exception: extends RuntimeException (caller may handle)

• Best practice: add custom exception code field for API error codes

• Spring's @ResponseStatus on custom exception auto-maps to HTTP status code

// Custom unchecked exceptions for backend APIs public class OrderNotFoundException extends
RuntimeException { private final String orderId; public OrderNotFoundException(String id) {
super("Order not found: " + id); [Link] = id; } public String getOrderId() { return
orderId; } } public class InsufficientStockException extends RuntimeException { public
InsufficientStockException(String sku, int requested, int available) {
super([Link]("SKU %s: requested %d, available %d", sku, requested, available)); } }
// Service usage public Order getOrder(String id) { return [Link](id)
.orElseThrow(() -> new OrderNotFoundException(id)); }

■ Real-Time Backend Example

Microservice defines custom exceptions: OrderNotFoundException (404), InsufficientStockException (409),


PaymentDeclinedException (402). Global @ControllerAdvice maps each to correct HTTP status and error
response body.
■ SECTION 6 — MULTITHREADING

6.1. Thread & Runnable | Thread Lifecycle

Definition
A Thread is a lightweight unit of execution. Java supports multithreading via: extending Thread class or
implementing Runnable interface (preferred). Thread states: NEW → RUNNABLE → RUNNING →
BLOCKED/WAITING → DEAD.

Key Points
• Thread extends Object: start() launches thread; run() contains task (don't call run() directly)

• Runnable is preferred: Java single inheritance — class can still extend another class

• Callable (Java 5+): like Runnable but returns a value and can throw checked exceptions

• Thread states: NEW (created), RUNNABLE (ready), RUNNING (executing), BLOCKED (waiting for lock),
WAITING (indefinite), TIMED_WAITING, DEAD (completed)

• sleep(ms) — pauses current thread; join() — waits for another thread to finish

• daemon threads: background threads; JVM exits when only daemon threads remain (GC is daemon)

// Runnable preferred (allows extending another class) public class OrderProcessor


implements Runnable { private final Order order; public OrderProcessor(Order o) {
[Link] = o; } @Override public void run() { [Link]("Processing: " +
[Link]() + " on " + [Link]().getName()); // payment, inventory update,
email notification } } // Thread pool (preferred over raw Thread) ExecutorService pool =
[Link](10); for (Order o : pendingOrders) { [Link](new
OrderProcessor(o)); } [Link]();

■ Real-Time Backend Example

Order fulfillment service uses a fixed thread pool of 10 threads to process orders concurrently. Each
OrderProcessor runs on a separate thread — 10x throughput vs sequential. ExecutorService manages thread
lifecycle, pool reuse, and graceful shutdown.

6.2. synchronized & volatile | Thread Safety

Definition
synchronized: ensures only one thread executes a block/method at a time (mutual exclusion). volatile: ensures
visibility — changes made by one thread are immediately visible to all others; does NOT provide atomicity.

Key Points
• synchronized method: locks on 'this' object; static synchronized: locks on Class object

• synchronized block: finer granularity — lock only the critical section, not entire method

• volatile: prevents thread-local caching (CPU cache); use for flags, stop conditions

• volatile is NOT a replacement for synchronized — no compound actions (check-then-act)

• Deadlock: two threads each holding a lock the other needs — circular wait

• Avoid deadlock: consistent lock ordering, timeout-based locks (tryLock), avoid nested locks

• Atomic classes (AtomicInteger, AtomicLong): lock-free thread-safe operations


// Thread-safe inventory counter public class InventoryService { private final Object lock
= new Object(); private int stockCount; private volatile boolean serviceActive = true; //
visibility only // synchronized block (fine-grained lock) public boolean reserveItem(int
qty) { synchronized (lock) { if (stockCount >= qty) { stockCount -= qty; return true; }
return false; } } // AtomicInteger: lock-free, better performance private AtomicInteger
atomicStock = new AtomicInteger(100); public boolean reserveAtomic(int qty) { return
[Link](-qty) >= 0; } }

■ Real-Time Backend Example

Flash sale inventory service: synchronized block prevents overselling when multiple concurrent requests try to
reserve the last unit. AtomicInteger preferred for high-throughput counters (no blocking). volatile flag used for
graceful shutdown of background worker threads.
■ SECTION 7 — JAVA 8 FEATURES

7.1. Lambda Expressions & Functional Interfaces

Definition
A Lambda expression is an anonymous function that implements a @FunctionalInterface (an interface with
exactly one abstract method). Syntax: (parameters) -> expression or { body }.

Key Points
• Functional interfaces: Predicate<T>, Function<T,R>, Consumer<T>, Supplier<T>, BiFunction<T,U,R>

• Predicate: takes T, returns boolean (test())

• Function: takes T, returns R (apply())

• Consumer: takes T, returns void (accept())

• Supplier: takes nothing, returns T (get())

• Method reference: Class::method — shorthand for lambda that just calls one method

• 4 method ref types: static (Class::staticMethod), instance (obj::method), class instance


(Class::instanceMethod), constructor (Class::new)

import [Link].*; // Lambda as Predicate Predicate<Order> isHighValue = order ->


[Link]() > 1000.0; Predicate<Order> isDelivered = order ->
"DELIVERED".equals([Link]()); Predicate<Order> highValueDelivered =
[Link](isDelivered); // Lambda as Function Function<String, Order> loadOrder = id
-> [Link](id).orElseThrow(); // Method references List<String> orderIds =
[Link]() .map(Order::getId) // class instance method ref
.collect([Link]()); // Sort with lambda comparator [Link]((o1, o2) ->
[Link]([Link](), [Link]())); // or:
[Link]([Link](Order::getAmount).reversed());

■ Real-Time Backend Example

Product filter API: multiple Predicates composed with .and()/.or() for dynamic filtering (price range, category,
availability). OrderMapper uses Function to transform entity to DTO. Notification service uses Consumer to
send emails to each order.

7.2. Stream API

Definition
Streams provide a functional, declarative way to process collections. A Stream is a sequence of elements
supporting sequential and parallel aggregate operations. Streams are lazy — intermediate operations execute only
when a terminal operation is invoked.

Key Points
• Intermediate ops (lazy): filter(), map(), flatMap(), sorted(), distinct(), limit(), skip(), peek()

• Terminal ops (eager): collect(), forEach(), reduce(), count(), findFirst(), anyMatch()/allMatch()/noneMatch(),


min()/max()

• Streams cannot be reused after terminal operation — IllegalStateException

• parallelStream(): uses ForkJoinPool for parallel processing; not always faster (overhead for small data)

• Collectors: toList(), toSet(), toMap(), groupingBy(), joining(), counting(), summingDouble()

• flatMap: flattens Stream<List<T>> → Stream<T>


• reduce: folds stream into single value; identity element + BinaryOperator

List<Order> orders = [Link](); // Filter + Map + Collect List<String>


activeOrderIds = [Link]() .filter(o -> !"CANCELLED".equals([Link]())) //
filter .sorted([Link](Order::getAmount).reversed()) // sort .limit(10)
// top 10 .map(Order::getId) // map to ID .collect([Link]()); // Group orders by
status Map<String, List<Order>> byStatus = [Link]()
.collect([Link](Order::getStatus)); // Total revenue double totalRevenue =
[Link]() .filter(o -> "DELIVERED".equals([Link]()))
.mapToDouble(Order::getAmount) .sum(); // FlatMap: all items across all orders
List<OrderItem> allItems = [Link]() .flatMap(o -> [Link]().stream())
.collect([Link]());

■ Real-Time Backend Example

Order analytics service uses streams to calculate daily revenue (filter+mapToDouble+sum), group orders by
status for dashboard, find top 10 customers by spend, and build category-wise sales reports using
groupingBy+summingDouble.

7.3. Optional

Definition
Optional<T> is a container that may or may not hold a non-null value. It is designed to avoid NullPointerException
and explicitly represents the concept of 'absent value'.

Key Points
• [Link](val) — non-null value; [Link](val) — nullable; [Link]()

• isPresent() / isEmpty() (Java 11) — check presence

• get() — returns value, throws NoSuchElementException if empty (avoid without check)

• orElse(default) — return value or default; orElseGet(Supplier) — lazy default

• orElseThrow(Supplier) — throw custom exception if empty

• map() / flatMap() — transform value if present

• ifPresent(Consumer) — execute if present

• Optional should NOT be used as method parameters or in fields — only as return type

// Repository returns Optional public Optional<Order> findById(String id) { return


[Link](id); // Spring Data returns Optional } // Service layer uses Optional
idiomatically public OrderDTO getOrderDetails(String orderId) { return
[Link](orderId) .map(orderMapper::toDTO) // transform if present
.orElseThrow(() -> new OrderNotFoundException(orderId)); } // Chain Optional operations
String city = [Link](email) .map(User::getAddress) .map(Address::getCity)
.orElse("Unknown");

■ Real-Time Backend Example

Spring Data JPA returns Optional<Order> from findById(). Service layer chains .map() for DTO conversion and
.orElseThrow() for consistent 404 responses — eliminating explicit null checks throughout the codebase.
■ QUESTION COVERAGE CHECKLIST
All questions from both PDFs are mapped below. PDF-1 covers Java Basics + OOP. PDF-2 covers Collections
Framework + Exceptions + advanced topics.

■ PDF-1 Questions (Java Basics + OOP)


■ What is Java? → 1.1 — What is Java | Features
■ Features/characteristics of Java (11 features) → 1.1 — What is Java | Features
■ What is JVM? → 1.2 — JVM vs JRE vs JDK
■ What is JDK? → 1.2 — JVM vs JRE vs JDK
■ What is JRE? → 1.2 — JVM vs JRE vs JDK
■ Difference between JVM, JRE, JDK → 1.2 — JVM vs JRE vs JDK
■ JVM Architecture (Class Loader, Memory, Execution Engine) → 1.2 & 1.3
■ Memory areas of JVM (Method Area, Heap, Stack, PC, Native) → 1.3 — JVM Memory Areas
■ What is Class Loader? Types of Class Loaders? → 1.2 — JVM (Class Loader section)
■ Delegation Model in class loading → 1.2 — JVM vs JRE vs JDK
■ What is Bytecode? → 1.2 — JVM vs JRE vs JDK
■ Difference between Interpreter and JIT Compiler → 1.2 — JVM vs JRE vs JDK
■ What is Garbage Collection? → 1.4 — Garbage Collection
■ Types of Garbage Collectors (Serial, Parallel, CMS, G1, ZGC) → 1.4 — Garbage Collection
■ What is finalize()? Why deprecated? → 1.4 — Garbage Collection
■ What are data types in Java? Primitives vs Reference? → 1.5 — Data Types
■ Widening vs Narrowing type conversion → 1.5 — Data Types
■ What is type casting in Java? → 1.5 — Data Types
■ What are operators in Java? (Arithmetic, Logical, Bitwise) → 1.6 — Operators
■ Bitwise operators and real-world use → 1.6 — Operators
■ What are arrays in Java? → 1.7 — Arrays
■ 2D array vs Jagged array → 1.7 — Arrays
■ Control flow: if-else, switch, loops → 1.8 — Control Flow
■ Difference between while and do-while → 1.8 — Control Flow
■ break vs continue → 1.8 — Control Flow
■ What are methods? Parameters, return types → 1.9 — Methods
■ Method overloading → 1.9 — Methods / 2.5 Polymorphism
■ What is varargs? → 1.9 — Methods
■ Access modifiers (private/default/protected/public) → 1.10 — Access Modifiers
■ What are Wrapper classes? Autoboxing/Unboxing? → 1.11 — Wrapper Classes
■ Integer cache (-128 to 127) trap → 1.11 — Wrapper Classes
■ static keyword (variable, method, block, class) → 1.12 — static Keyword
■ What are 4 pillars of OOP? → 2.1 — 4 Pillars of OOP
■ What is a Class? What is an Object? → 2.2 — Class & Object
■ What is a Constructor? Types? → 2.2 — Class & Object | Constructor
■ Constructor chaining (this(), super()) → 2.2 & 2.7
■ Copy constructor → 2.2 — Class & Object | Constructor
■ What is Encapsulation? Data hiding? → 2.3 — Encapsulation
■ What is Inheritance? Types? → 2.4 — Inheritance & Types
■ Why Java does not support multiple inheritance with classes? → 2.4 — Inheritance & Types
■ super keyword — uses → 2.4 — Inheritance & Types
■ What is Polymorphism? Compile-time vs Runtime? → 2.5 — Polymorphism
■ Difference between method overloading and overriding → 2.5 — Polymorphism
■ Rules for method overriding → 2.5 — Polymorphism
■ Covariant return type → 2.5 — Polymorphism
■ What is Abstraction? → 2.1 & 2.6
■ Abstract class vs Interface → 2.6 — Abstract Class vs Interface
■ Can interface have constructor? Can abstract class? → 2.6 — Abstract Class vs Interface
■ Default methods and static methods in Interface (Java 8) → 2.6 — Abstract Class vs Interface
■ this keyword — uses → 2.7 — 'this' Keyword
■ What is Upcasting? Downcasting? ClassCastException? → 2.8 — Upcasting & Downcasting
■ instanceof operator → 2.8 — Upcasting & Downcasting
■ What is String in Java? Why immutable? → 3.1 — String Immutability & String Pool
■ What is String Pool? → 3.1 — String Immutability & String Pool
■ String vs StringBuilder vs StringBuffer → 3.2 — String vs StringBuilder vs StringBuffer
■ Important String methods (length, charAt, split, etc.) → 3.3 — Important String Methods
■ equals() vs == for Strings → 3.1 — String Immutability & String Pool
■ What is Wrapper class? → 1.11 — Wrapper Classes
■ What is Multithreading? → 6.1 — Thread & Runnable
■ Thread vs Runnable — which is preferred? → 6.1 — Thread & Runnable
■ Thread lifecycle states → 6.1 — Thread & Runnable
■ synchronized keyword → 6.2 — synchronized & volatile
■ volatile keyword → 6.2 — synchronized & volatile
■ Common Errors (StackOverflowError, OutOfMemoryError, etc.) → 5.1 Exception Hierarchy

■ PDF-2 Questions (Collections + More OOP)


■ What is Java Collection Framework? Core interfaces? → 4.0 — Collections intro
■ Difference between Collection (interface) and Collections (utility class) → 4.0 — Collections intro
■ ArrayList — internal working, default capacity, how it grows → 4.1 — ArrayList vs LinkedList
■ ArrayList methods (add, remove, get, set, contains, isEmpty) → 4.1 — ArrayList vs LinkedList
■ ArrayList vs LinkedList — comparison table → 4.1 — ArrayList vs LinkedList
■ HashMap — internal working (hashing, buckets, chaining) → 4.2 — HashMap
■ HashMap — load factor, resize, treeification (Java 8) → 4.2 — HashMap
■ HashMap vs Hashtable → 4.2 — HashMap
■ HashMap vs ConcurrentHashMap → 4.2 — HashMap
■ LinkedHashMap vs TreeMap → 4.2 — HashMap
■ HashMap methods (put, get, getOrDefault, computeIfAbsent) → 4.2 — HashMap
■ What is HashSet? Internal structure? → 4.3 — HashSet vs LinkedHashSet vs TreeSet
■ HashSet vs LinkedHashSet vs TreeSet → 4.3 — HashSet vs LinkedHashSet vs TreeSet
■ Queue — offer/poll/peek vs add/remove/element → 4.4 — Queue, Deque & Stack
■ PriorityQueue — how it works → 4.4 — Queue, Deque & Stack
■ Deque / ArrayDeque → 4.4 — Queue, Deque & Stack
■ Stack — legacy vs ArrayDeque → 4.4 — Queue, Deque & Stack
■ What is Iterator? How to use? → 4.5 — Iterator
■ Fail-Fast vs Fail-Safe iterators → 4.5 — Iterator | Fail-Fast vs Fail-Safe
■ ConcurrentModificationException — when/why? → 4.5 — Iterator | Fail-Fast vs Fail-Safe
■ CopyOnWriteArrayList — when to use? → 4.5 — Iterator | Fail-Fast vs Fail-Safe
■ Comparable vs Comparator → 4.6 — Comparable vs Comparator
■ [Link]() chaining (Java 8) → 4.6 — Comparable vs Comparator
■ Exception hierarchy — Throwable, Error, Exception → 5.1 — Exception Hierarchy
■ Checked vs Unchecked exceptions → 5.1 — Exception Hierarchy
■ try-catch-finally execution order → 5.2 — try-catch-finally
■ try-with-resources — how it works → 5.2 — try-catch-finally
■ Multi-catch (catch multiple exceptions) → 5.2 — try-catch-finally
■ throw vs throws → 5.3 — throw vs throws | Custom Exceptions
■ Custom exception creation → 5.3 — throw vs throws | Custom Exceptions
■ Exception chaining → 5.3 — throw vs throws | Custom Exceptions
■ What is Lambda expression? → 7.1 — Lambda Expressions
■ Functional interfaces: Predicate, Function, Consumer, Supplier → 7.1 — Lambda Expressions
■ Method references (4 types) → 7.1 — Lambda Expressions
■ Stream API — intermediate vs terminal operations → 7.2 — Stream API
■ Stream operations: filter, map, flatMap, collect, groupingBy → 7.2 — Stream API
■ parallelStream() — when to use? → 7.2 — Stream API
■ Optional — orElse, orElseThrow, map, flatMap → 7.3 — Optional
■ Default methods in interface (Java 8) → 2.6 — Abstract Class vs Interface
■ Covariant return type in method overriding → 2.5 — Polymorphism
■ RAPID REVISION SHEET — Last Day Review

Java Abstract Class vs Interface Fail-Fast


High-level, OOP, platform-independent, Abstract: extends one, has state, Throws ConcurrentModificationException
WORA — write once run anywhere via constructor. Interface: implements many, if collection modified during iteration
JVM. no state, no constructor. (ArrayList, HashMap).
JDK super Fail-Safe
Full dev kit = JRE + javac + tools. Refers to parent: super() calls parent Works on snapshot, no exception
Needed to write and compile Java. constructor (must be first line); (CopyOnWriteArrayList,
[Link]() calls parent method. ConcurrentHashMap).
JRE this Comparable
Runtime only = JVM + class libraries. Refers to current object. this() chains Implement in class for natural order.
Needed to run pre-compiled Java. constructor. return this enables method compareTo(). Used in [Link]().
chaining.
JVM Upcasting/Downcasting Comparator
Virtual machine that executes bytecode; Upcast implicit (safe). Downcast explicit External sort logic. Multiple strategies. Co
NOT cross-platform (OS-specific — always check instanceof first. [Link]().thenComparing().
implementation).
Class Loader String Immutability Checked Exception
Loads .class into JVM: Bootstrap → String cannot change once created. New Compiler-enforced. Must catch or declare
Extension → Application (delegation object created on every modification. (throws). E.g., IOException,
model). SQLException.
JVM Memory String Pool Unchecked Exception
Method Area (static/class), Heap JVM reuses string literals. new String() RuntimeException. Optional handling.
(objects), Stack (frames/locals), PC, bypasses pool. intern() moves to pool. E.g., NullPointerException,
Native Stack. IllegalArgumentException.
JIT Compiler StringBuilder finally
Compiles frequently executed bytecode Mutable, NOT thread-safe, fast. Use for Always executes after try-catch. Ideal for
to native machine code for performance. string building in loops. cleanup. Cannot suppress with return.
Garbage Collector StringBuffer try-with-resources
Auto-frees unreachable heap objects. Mutable, thread-safe (synchronized). Use Auto-closes AutoCloseable. Resources
G1GC default; ZGC ultra-low pause. when multiple threads append. closed in reverse order. Java 7+.
Primitives ArrayList Custom Exception
8 types: byte, short, int, long, float, Dynamic array. O(1) get, O(n) Extend RuntimeException (unchecked)
double, char, boolean. insert-middle. Default capacity 10, grows or Exception (checked). Add error code
50%. field.
Autoboxing LinkedList Thread vs Runnable
Automatic conversion between primitives Doubly-linked. O(1) insert/delete Runnable preferred: allows class to
and wrapper objects (int ↔ Integer). head/tail, O(n) access. Also a Deque. extend something else. Thread = is-a
Thread.
Integer Cache HashMap synchronized
Java caches Integer -128 to 127. Use Key-value, O(1) avg. Backed by array of Mutual exclusion. Locks object/class.
.equals() for comparison, not ==. buckets + chaining. Null key allowed. Prevents race conditions.
static HashMap internals volatile
Belongs to class, not instance. static hashCode() → bucket; equals() → Visibility guarantee. No CPU caching.
block runs once at class loading. resolve collision. Java 8: tree at 8+ NOT atomic for compound operations.
collisions.
Encapsulation HashSet Lambda
Private fields + public getters/setters. Unique elements, backed by HashMap. Anonymous function: (params) -> body.
Protects data, enforces validation. No order. O(1) operations. Implements @FunctionalInterface.
Inheritance TreeSet/TreeMap Stream API
Child extends parent (IS-A). Multiple Sorted (natural or Comparator). O(log n). Functional pipeline: filter → map →
inheritance not supported for classes. Uses Red-Black Tree internally. collect. Lazy intermediate, eager
terminal.
Polymorphism LinkedHashMap Optional
Overloading = compile-time (same name, HashMap + insertion order. Used for LRU Null-safe container. orElseThrow() for
diff params). Overriding = runtime (child cache (access-order=true). custom exceptions. Never use as
redefines parent method). parameter/field.
Abstraction ConcurrentHashMap Default Method
Hide implementation. Abstract class: Thread-safe HashMap. Segment-level Interface method with body (Java 8).
partial. Interface: full contract. locking. Replaces Hashtable. Allows interface evolution without
breaking implementors.

■ Java Backend Interview Master Guide — Compiled from PDF-1 (189 pages) + PDF-2 (104 pages) | All concepts backend-focused |
Code-heavy | Ready for 8–12 YOE Interviews

You might also like