Java Interview MasterGuide
Java Interview MasterGuide
■ 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
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
// Java lifecycle: .java → javac → .class (bytecode) → JVM → Output public class
OrderService { public static void main(String[] args) { [Link]("Order Service
Running on JVM"); } }
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.
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
• 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
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.
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
// 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 }
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
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.
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)
• Java is strictly typed — no implicit conversion from larger to smaller type without cast
• 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
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.
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++)
• Bitwise: &(AND), |(OR), ^(XOR), ~(NOT), <<(left shift), >>(right shift), >>>(unsigned right shift)
• Bitwise left shift << n = multiply by 2^n (fast); >> n = divide by 2^n
// 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";
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.
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)
• Jagged array: each row can have different column count (irregular 2D array)
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
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.
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
// 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); }
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
• Varargs (variable args): void log(String... msgs) — must be last parameter, treated as array
• void return type = no return value; other types must return a matching value
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.
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]); } }
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.
Key Points
• 8 wrappers: Byte, Short, Integer, Long, Float, Double, Character, Boolean
• 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()
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.
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
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
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
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
• Constructor chaining: this() calls same-class constructor; super() calls parent constructor
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; } }
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
• JavaBean convention: private fields + public getters + public setters + no-arg constructor
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.
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)
• Method hiding: if parent and child both have a static method with same signature, NOT overriding
• 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); } }
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
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.
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
Constructor Yes No
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)
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);
Builder pattern in Order domain object uses 'return this' for fluent API: new
OrderBuilder().withProduct(p).withQty(2).withAddress(a).build().
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();
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
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
• == 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);
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.
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
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.
// 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");
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.
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
// 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)
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.
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
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.
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
• 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
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.
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)
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.
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
• CopyOnWriteArrayList: safe for concurrent reads, expensive writes (creates new array)
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.
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'
• compareTo() returns: negative (this < other), 0 (equal), positive (this > other)
// 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
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
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
• Checked: must use try-catch or declare with throws; enforced at compile time
// 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"); }
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.
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)
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.
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);
• Best practice: add custom exception code field for API error codes
// 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)); }
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)
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.
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
• Deadlock: two threads each holding a lock the other needs — circular wait
• Avoid deadlock: consistent lock ordering, timeout-based locks (tryLock), avoid nested locks
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
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>
• Method reference: Class::method — shorthand for lambda that just calls one method
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.
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()
• parallelStream(): uses ForkJoinPool for parallel processing; not always faster (overhead for small data)
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]()
• Optional should NOT be used as method parameters or in fields — only as return type
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.
■ 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