A Java handbook · zero to interview depth

Java Ground Up

Every Java concept you need for a Software Engineer interview, in order, starting from what the JVM actually is. Read it start to finish, or jump to the chapter you need — each one ends with the angle an interviewer takes on it.

I. What Java Actually Is
Chapter 01

Java in one page

Java is a statically typed, object-oriented, garbage-collected language that compiles to an intermediate form called bytecode, which is then executed by a virtual machine. That one sentence contains everything that makes Java distinctive, and the rest of this chapter unpacks it.

Statically typed means every variable has a type known at compile time, and the compiler rejects code that violates it. int x = "hello" never runs, because it never compiles. This is the opposite of Python or JavaScript, where the mistake surfaces at runtime — possibly in production, possibly months later.

Garbage-collected means you never free memory. You allocate objects with new and the JVM reclaims them once nothing references them. You cannot leak memory the way C can, but — as you will see much later — you can absolutely leak by keeping references you forgot about, which is a different and more subtle problem.

Compiles to bytecode is the famous part. Java source is not compiled to machine code for your specific processor. It is compiled to a portable instruction set that any Java Virtual Machine can execute. That is what "write once, run anywhere" means, and it is why the same .jar file runs unchanged on your laptop, on a Linux server, and inside a container.

Where Java is actually used

Java dominates in places where systems are large, long-lived and run on servers: banking and payments, e-commerce backends, enterprise systems, big-data infrastructure (Hadoop, Kafka, Elasticsearch and Cassandra are all JVM projects), and Android. It is not the language people reach for to write a quick script, and it is rarely the fastest to prototype in. Its strengths are the ones that matter at year three of a codebase with forty engineers: strong typing, mature tooling, excellent observability, and a runtime that has been optimised for twenty-five years.

Interview angle

Interviewers rarely ask "what is Java" directly, but they routinely ask what bytecode is, why the JVM exists, and what platform independence actually buys you. Being able to state the compile-to-bytecode-then-interpret-and-JIT pipeline in two sentences is a small thing that signals you understand the runtime rather than just the syntax.

Chapter 02

JDK, JRE and JVM — the three you must not confuse

These three acronyms are the most commonly asked and most commonly muddled thing in early Java interviews. They are nested: the JDK contains the JRE, and the JRE contains the JVM.

JVM — Java Virtual Machine. The engine that executes bytecode. It is a specification, and there are several implementations (HotSpot is the common one; others include OpenJ9 and GraalVM). The JVM is what loads your classes, manages memory, runs garbage collection, and compiles hot code to native instructions. It executes bytecode and nothing else — it does not know or care that your source was Java. Kotlin, Scala, Groovy and Clojure all compile to the same bytecode and run on the same JVM.

JRE — Java Runtime Environment. The JVM plus the standard library — the classes in java.lang, java.util, java.io and the rest. This is what you need to run a Java application. Historically it was distributed separately; since Java 11 there is no standalone JRE download, and you either ship a JDK or build a trimmed runtime with jlink.

JDK — Java Development Kit. The JRE plus the development tools: the compiler javac, the launcher java, the disassembler javap, the diagnostic tools jcmd, jstack and jmap, and the packaging tool jar. This is what you install to write Java.

Shell
JDK  = JRE + javac, javap, jcmd, jstack, jmap, jar ...   (to DEVELOP)
  JRE  = JVM + standard library (java.lang, java.util ...)    (to RUN)
    JVM = the execution engine for bytecode                    (to EXECUTE)

# check what you have
java -version     # the runtime
javac -version    # the compiler - only present if you have a JDK
Interview angle

The one-line answer: JVM runs bytecode, JRE is the JVM plus the standard library, JDK is the JRE plus the development tools. The follow-up is usually "can you run Java without a JDK?" — historically yes with a JRE, and today you ship a JDK or a jlink-built runtime image.

Chapter 03

How your code actually runs

Understanding the execution pipeline explains an enormous amount of later behaviour — why the first request to a freshly started service is slow, why stack traces look the way they do, and why performance measurements taken in the first few seconds are meaningless.

Step 1 — compilation

javac Main.java reads your source, checks types, and produces Main.class — a binary file containing bytecode, a compact instruction set for a stack-based virtual machine. Crucially, javac does almost no optimisation. It is a translator, not an optimiser. All the clever work happens later, at runtime.

Step 2 — class loading

When you run java Main, the JVM starts and loads classes lazily — not all at once, but the first time each is actually used. Loading involves finding the .class file on the classpath, verifying the bytecode is safe (the verifier proves it cannot corrupt memory, which is why the JVM can run untrusted code), and preparing static fields.

Step 3 — interpretation, then JIT compilation

The JVM starts by interpreting bytecode one instruction at a time, which is slow but starts instantly. While interpreting, it profiles: which methods run often, which branches are taken, which types actually appear at each call site. Once a method is called enough times, the JIT compiler compiles it to native machine code, using the collected profile to optimise aggressively — inlining calls, eliminating dead branches, even removing allocations entirely.

This is why Java is often described as slow and often benchmarks as fast: both are true at different moments. A cold JVM is genuinely slow; a warmed-up one can approach C. The transition is called warmup, and it takes seconds to minutes depending on the workload.

Pipeline
Main.java
   | javac        (type-check, translate - almost no optimisation)
   v
Main.class  (bytecode - portable, verifiable)
   | java         (JVM starts)
   v
class loading -> verification -> INTERPRET (slow, starts instantly, profiles)
                                     |
                                     | method gets hot
                                     v
                                JIT COMPILE to native code (fast)
Interview angle

This pipeline is the root of several real interview answers. Why is the first request slow? The JVM is interpreting and has not JIT-compiled the hot path yet. Why does a naive microbenchmark lie? Because without warmup you measured the interpreter. Why ramp traffic to a new instance gradually? Because a cold JVM sent full production load will time out.

Chapter 04

Your first program, line by line

Every line of the canonical first program is there for a reason, and each one is a question someone has been asked in an interview.

Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

public class Main — Java requires a class for everything; there are no free-standing functions. The file must be named Main.java if the public class is Main, because the compiler maps public class names to filenames.

public — the JVM must be able to call this method from outside the class, so it cannot be private.

static — this is the one that matters. static means the method belongs to the class, not to an instance. The JVM needs to call main before any object exists, so it cannot require an instance to call it on. This is also why you cannot reference instance fields directly from main — there is no this.

void — returns nothing. The exit code comes from System.exit() or from normal termination, not from a return value.

String[] args — command-line arguments. The name is convention; the type is not.

What actually happens when you run it

Shell
javac Main.java     # -> Main.class
java Main           # JVM starts, finds Main on the classpath,
                    # loads it, verifies it, initialises it,
                    # then invokes main(String[])

# note: `java Main` - the CLASS name, not the file name. No .class extension.
# Java 11+ can also run a single file directly:  java Main.java
Interview angle

Two classic beginner-level interview questions come from here. Why is main static? Because the JVM must call it before any instance exists. Can you overload main? Yes, but the JVM only ever calls the String[] version as the entry point; the others are ordinary methods.

Chapter 05

Primitives, wrappers and the type system

Java has eight primitive types, and everything else is an object. This split is unusual among modern languages and it has consequences that reach all the way into performance discussions.

Primitives
byte    1 byte    -128 .. 127
short   2 bytes   -32,768 .. 32,767
int     4 bytes   about -2.1 billion .. 2.1 billion       <- the default for whole numbers
long    8 bytes   about -9.2e18 .. 9.2e18                 <- literal needs L: 10_000_000_000L
float   4 bytes   ~7 decimal digits of precision          <- literal needs f: 3.14f
double  8 bytes   ~15 decimal digits                      <- the default for decimals
char    2 bytes   a single UTF-16 code unit, 0 .. 65,535
boolean            true / false (size is JVM-dependent)

Primitives hold their value directly. Objects hold a reference to a value on the heap. An int is four bytes; an Integer is a reference (typically 4 or 8 bytes) pointing at a heap object that costs 16 bytes to hold those same four bytes of data. That roughly sixfold difference is why numeric-heavy code uses int[] rather than List<Integer>.

Wrappers and autoboxing

Each primitive has a wrapper class — int/Integer, long/Long, and so on — because generics and collections can only hold objects. List<int> is not legal; List<Integer> is. Autoboxing is the compiler silently converting between them.

Java
Integer boxed = 5;        // compiler inserts Integer.valueOf(5)
int unboxed = boxed;      // compiler inserts boxed.intValue()

Map<String,Integer> m = new HashMap<>();
int v = m.get("missing"); // NullPointerException - unboxing a null
                          // and the line looks like arithmetic, not a null check

The Integer cache — a classic trap

Integer.valueOf returns cached, shared instances for values from −128 to 127. So reference comparison accidentally works in that range and silently breaks outside it.

Java
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b);       // true  - same cached object
System.out.println(c == d);       // false - two distinct objects
System.out.println(c.equals(d));  // true  - the correct comparison
Interview angle

This appears in interviews constantly, and the right answer has two parts: state the cache range, then state the rule it implies — always compare boxed values with equals, never ==. The follow-up is usually "why does the cache exist?": small integers dominate real programs, so caching them removes most boxing allocation.

Chapter 06

Pass-by-value — the most misunderstood rule in Java

Java is always pass-by-value. There is no pass-by-reference. This trips people up because for objects, the value being copied is the reference.

When you pass an object to a method, the method receives its own copy of the pointer, aimed at the same heap object. So the method can mutate what you passed — both references point at the same object — but it cannot reassign your variable, because reassigning only changes the method's private copy of the pointer.

Java
static void mutate(StringBuilder sb)   { sb.append("!"); }
static void reassign(StringBuilder sb) { sb = new StringBuilder("x"); }

StringBuilder s = new StringBuilder("hi");
mutate(s);    System.out.println(s);   // hi!   - caller sees the mutation
reassign(s);  System.out.println(s);   // hi!   - unchanged, not "x"

This is exactly why a swap(a, b) method is impossible in Java. The method can swap its own two local copies of the references all it likes; the caller's variables are untouched.

For primitives the mechanism is identical, just more obvious: the four bytes of the int are copied, so nothing the method does can be seen by the caller.

Interview angle

Say it precisely: "the reference is passed by value." Saying "objects are passed by reference" is the wrong answer even though it predicts most behaviour correctly — and interviewers listen for exactly that phrasing. If you need swap-like behaviour, return a new object holding both values, or pass a mutable holder.

Chapter 07

Operators, control flow and modern switch

Most of this is unsurprising if you have written any C-family language, so this chapter covers only the parts that carry Java-specific traps or that changed recently.

Integer overflow is silent

Java integer arithmetic wraps on overflow with no exception. Integer.MAX_VALUE + 1 is Integer.MIN_VALUE. The classic production bug is (low + high) / 2 in a binary search over a large array — write low + (high - low) / 2 instead. Use Math.addExact when you want a failure rather than a wrong number.

Floating point is not decimal

double is IEEE-754 binary, so 0.1 has no exact representation, exactly as 1/3 has no exact decimal one. 0.1 + 0.2 is 0.30000000000000004. Never compare doubles with ==, and never use them for money — use BigDecimal or an integer count of minor units (paise, cents).

The modern switch

The old switch statement falls through by default, which is a permanent source of bugs. The arrow form removes fall-through entirely, and the switch expression returns a value — which lets the compiler enforce that you handled every case.

Java
// old: falls through unless you break
switch (day) {
    case SATURDAY:
    case SUNDAY: type = "weekend"; break;
    default:     type = "weekday";
}

// modern: an expression, no fall-through, exhaustive
String type = switch (day) {
    case SATURDAY, SUNDAY -> "weekend";
    default               -> "weekday";
};

// pattern matching for instanceof - no cast needed
if (o instanceof String s && s.length() > 3) {
    use(s);            // s is already a String here
}
Interview angle

Exhaustiveness is the real prize and it comes back in Chapter 17 with sealed types: a switch expression over a closed set of types needs no default, and adding a new variant later breaks the build at every such switch. That turns a runtime surprise into a compile-time checklist, which is a genuinely strong thing to mention.

II. The Object Model
Chapter 08

Classes, constructors and initialization order

A class is a template; an object is an instance of it. A constructor initialises that instance. It has no return type, its name matches the class, and its first statement is always a call to another constructor — either this(...) to chain within the class, or super(...) to the parent. If you write neither, the compiler inserts an implicit super(), which is why a parent without a no-argument constructor forces every child to call super explicitly.

The order things run in

This sequence is asked often because getting it wrong produces bugs that look impossible.

Order
CLASS level - once, lazily, on first active use:
  1. static fields and static blocks, top to bottom in source order

INSTANCE level - every time you construct:
  2. the SUPERCLASS constructor runs to completion
  3. instance field initialisers and instance blocks, in source order
  4. the constructor body

Step 2 running before step 3 causes the classic trap: if a superclass constructor calls an overridable method, the subclass override runs before the subclass's fields are initialised, so it sees nulls and zeros.

Java
class Parent {
    Parent() { init(); }                 // dangerous
    void init() {}
}
class Child extends Parent {
    private String name = "set";
    @Override void init() { System.out.println(name); }   // prints null
}

The rule that follows: never call an overridable method from a constructor. Make such methods private, static or final.

Telescoping constructors

A chain of overloads with growing parameter lists becomes unreadable past three or four fields, and two same-typed parameters in the wrong order is a bug the compiler cannot catch. The two fixes are a static factory with a meaningful name (Money.ofMinor(1250, INR)) or a builder when many fields are optional.

Interview angle

Validate in the constructor and throw, so an object can never exist in an invalid state. That single habit — if it constructed, it is valid — removes an entire category of defensive checks from the rest of the codebase, and it is the reason to prefer constructors over setters for required fields.

Chapter 09

Inheritance and dynamic dispatch

class Child extends Parent creates an is-a relationship: a Child can be used anywhere a Parent is expected. Java allows single inheritance of classes — one parent only — but a class may implement many interfaces.

Polymorphism is the ability of a reference of the parent type to hold a child object and dispatch to the child's behaviour. The method that actually runs is decided at runtime based on the object's real type, not the reference's declared type. That is dynamic dispatch, and the JVM implements it with a virtual method table — a per-class array of method pointers.

Java
class Animal { String speak() { return "..."; } }
class Dog extends Animal { @Override String speak() { return "woof"; } }

Animal a = new Dog();
a.speak();          // "woof" - resolved from the OBJECT's type at runtime

The JIT often removes the indirection entirely: if profiling shows a call site only ever sees one type (it is monomorphic), the compiler inlines the target and guards it with a cheap type check. A call site seeing three or more types is megamorphic and stays an indirect jump — which blocks inlining and every optimisation inlining would have unlocked.

What you can and cannot change when overriding

  • The signature must match — same name, same parameter types.
  • The return type may be covariant (narrower than the parent's).
  • Access may widen but never narrow — a public method cannot become protected.
  • The override may throw fewer or narrower checked exceptions, never broader ones.
  • final methods cannot be overridden at all.

Always write @Override. It is optional, and it turns a typo that silently creates a brand-new method into a compile error.

Interview angle

Access cannot narrow because of the Liskov substitution principle: code holding a Parent reference must be able to call the method. Narrowing would break that guarantee, so the compiler rejects it — a rare case where a design principle is enforced by the language itself.

Chapter 10

Overloading, overriding and hiding

Three similar-looking mechanisms with completely different resolution rules. Confusing them produces bugs that read as impossible, so it is worth being precise.

Overriding replaces a superclass instance method. Resolved at runtime by the object's actual type. This is polymorphism.

Overloading is several methods with the same name and different parameter lists in the same class. Resolved at compile time by the static types of the arguments. The compiler picks the most specific applicable overload and bakes that choice into the bytecode.

Hiding applies to static methods and to fields. Neither is polymorphic. Redeclaring a static method in a subclass hides the parent's; which one runs depends on the reference type. Fields are never polymorphic at all — they are always resolved by the declared type.

Java
class A { static String who(){return "A";}  String name(){return "A";}  String f = "fA"; }
class B extends A { static String who(){return "B";} String name(){return "B";} String f = "fB"; }

A ref = new B();
ref.name();     // "B"  - overriding: dynamic dispatch on the object
ref.f;          // "fA" - fields are NOT polymorphic, resolved by reference type
A.who();        // "A"  - statics are hidden, not overridden

The overloading trap in collections

Java
List<Integer> list = new ArrayList<>(List.of(10, 20, 30));
list.remove(1);                      // removes INDEX 1 -> the value 20
list.remove(Integer.valueOf(1));     // removes the VALUE 1 (not present here)

Overload resolution prefers the primitive remove(int) over remove(Object), so autoboxing changes the meaning of the call. This is a real production bug, not a puzzle.

Interview angle

The compressed answer: overriding is runtime and polymorphic; overloading is compile-time and by static types; hiding applies to statics and fields and is neither. Interviewers often show a snippet like the one above and ask what it prints — being able to explain why, not just guess, is the difference.

Chapter 11

Abstract classes and interfaces

Before Java 8 the distinction was simple: interfaces held only method signatures, abstract classes could hold implementation and state. Default methods blurred that — an interface can now ship behaviour — but the distinction that survives is state.

  • An interface cannot have instance fields. A class can implement many.
  • An abstract class can hold instance fields and constructors. A class can extend only one.

So the modern rule: use an interface for a capability unrelated types can have, and an abstract class only when subtypes genuinely share mutable state or construction logic — typically the Template Method pattern, where the parent fixes an algorithm and subclasses fill in steps.

Why default methods exist

Not to make interfaces into classes, but for API evolution. Adding an abstract method to a published interface breaks every implementation in the world; adding a default method does not. That is how stream() was added to Collection without breaking the ecosystem.

Interfaces can also have static methods (factories belonging to the type) and, since Java 9, private methods to share code between defaults without exposing it.

The diamond, and how Java resolves it

If two interfaces supply the same default method, Java applies three rules in order: (1) a class wins over an interface — a concrete inherited method beats any default; (2) the most specific interface wins — a sub-interface beats its parent; (3) otherwise it is a compile error and you must override explicitly.

Java
interface A { default String hello(){ return "A"; } }
interface B { default String hello(){ return "B"; } }

class C implements A, B {
    @Override public String hello() {
        return A.super.hello();       // explicit resolution - the only way
    }
}
Interview angle

That third rule is why default methods did not reintroduce the C++ multiple-inheritance problem: Java refuses to guess. State is still single-inheritance, and behaviour conflicts are a compile-time error rather than a silent arbitrary choice.

Chapter 12

Encapsulation and access modifiers

Four levels, from most to least open:

Access
public           everywhere
protected        subclasses + the same package
(default)        the same package only        <- "package-private", no keyword
private          the declaring class only

Package-private is underused and valuable. It lets you expose a class to its collaborators without making it part of your public API, which keeps refactoring cheap. Anything public is a contract you must keep — so the right default is the narrowest access that works, widening only when a real caller needs it.

Encapsulation is about invariants, not about getters

The point is not mechanically wrapping every field in a getter and setter — that produces a class with no invariants and a lot of ceremony. The point is that the object controls its own state, so it can guarantee something about it. A BankAccount that exposes setBalance guarantees nothing; one that exposes debit(amount) can enforce that the balance never goes negative.

Java
// no invariant - the setter lets anyone break it
class Account { private long balance; public void setBalance(long b){ balance = b; } }

// the invariant is enforced by the object
class Account {
    private long balance;
    public void debit(long amount) {
        if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
        if (amount > balance) throw new InsufficientFundsException();
        balance -= amount;
    }
}
Interview angle

A useful review question: what does this class guarantee about itself? If the answer is "nothing, it is a bag of fields", it should probably be a record. If it does guarantee something, every mutator must preserve that guarantee — and a public setter almost never does.

Chapter 13

equals and hashCode — the contract that matters most

Every Java class inherits equals and hashCode from Object, where they are identity-based: two objects are equal only if they are the same instance. Overriding them defines logical equality — and doing it wrong is the single most commonly examined bug in Java interviews.

The equals contract

  • Reflexive — x.equals(x) is true.
  • Symmetric — x.equals(y) if and only if y.equals(x).
  • Transitive — if x equals y and y equals z, then x equals z.
  • Consistent — repeated calls agree while nothing changes.
  • x.equals(null) is always false.

The hashCode contract

One sentence: equal objects must return equal hash codes. The converse is not required — unequal objects may collide, and hash collections handle that by chaining.

What breaks when you violate it

Override equals without hashCode and you inherit the identity-based hash. So put hashes the key to bucket A. A later, logically equal lookup key hashes to bucket B, the map searches bucket B, finds nothing, and returns null — while the entry sits in bucket A, permanently unreachable and un-removable. It is simultaneously a correctness bug and a memory leak.

Java
class Key {
    final int id;
    Key(int id) { this.id = id; }
    @Override public boolean equals(Object o) { return o instanceof Key k && k.id == id; }
    // hashCode NOT overridden - broken
}
Map<Key,String> m = new HashMap<>();
m.put(new Key(1), "value");
m.get(new Key(1));         // null
m.containsKey(new Key(1)); // false

// correct pairing
@Override public int hashCode() { return Objects.hash(id); }

The second failure is mutating a key after insertion: the entry stays in the old bucket while the key now hashes elsewhere. Same result. This is why HashMap keys should be immutable.

Interview angle

Expect the follow-up "getClass() or instanceof in equals?" — getClass() guarantees symmetry but breaks with proxies and Hibernate subclasses; instanceof works with proxies but needs the class to be final, or a subclass adding a field breaks symmetry. For JPA entities the usual compromise is instanceof plus comparing only a stable business key.

Chapter 14

compareTo, toString and clone

compareTo

Comparable.compareTo defines the type's natural order and must be a total order: antisymmetric, transitive, and consistent. The optional-but-strongly-recommended clause is consistency with equals: x.compareTo(y) == 0 should mean x.equals(y).

Break that and sorted collections misbehave in a way that looks like a JDK bug. TreeSet and TreeMap decide membership using compareTo, never equals — so a TreeSet ordered by salary silently treats two different employees earning the same amount as duplicates and drops one.

Java
record Emp(String name, int salary) {}
Set<Emp> set = new TreeSet<>(Comparator.comparingInt(Emp::salary));
set.add(new Emp("asha", 100));
set.add(new Emp("bela", 100));
set.size();     // 1 - bela was treated as a duplicate

// fix: make the comparator a TOTAL order with a tie-breaker
Comparator<Emp> c = Comparator.comparingInt(Emp::salary).thenComparing(Emp::name);

A worse violation is a non-transitive comparator: TimSort detects the inconsistency and throws IllegalArgumentException: Comparison method violates its general contract! — but usually only on large inputs, because small arrays take a simpler sort path. So it passes every test and fails in production.

toString

Costs nothing to write and pays for itself in every log line and stack trace. Include the identifying fields. Never include secrets — passwords, tokens, full card numbers — because toString ends up in logs you do not control.

clone — the broken one

Worth being able to criticise: clone() is declared on Object, but Cloneable is a marker interface with no clone method; the default implementation is a shallow field copy that bypasses constructors, so invariants are not enforced; and it interacts badly with final fields. Prefer a copy constructor or a static copy factory — ordinary code that runs constructors, works with final fields, and makes shallow-versus-deep an explicit choice.

Interview angle

The one legitimate use of clone is arrays — arr.clone() is idiomatic, fast and correct, because arrays have no invariants to break.

Chapter 15

Immutability and defensive copies

An immutable object cannot change after construction. It is the single highest-leverage design habit in Java: immutable objects are automatically thread-safe, safe to cache and share, and safe as map keys.

The five rules

  • Make the class final (or the constructor private) so behaviour cannot be overridden.
  • Make every field private final.
  • Provide no setters or other mutators.
  • Defensively copy mutable inputs in the constructor.
  • Defensively copy mutable state on the way out of getters.

The last two are where people lose the point. Missing the copy in means the caller keeps a reference to your internal state and can mutate your object from outside. Missing the copy out means the caller mutates the object you handed back. Either one destroys immutability entirely — the class merely looks immutable.

Java
public final class Order {
    private final String id;
    private final List<Item> items;

    public Order(String id, List<Item> items) {
        this.id = id;
        this.items = List.copyOf(items);      // defensive copy IN
    }
    public List<Item> items() { return items; }  // already unmodifiable
    // if it were an ArrayList: return List.copyOf(items)
}

Safe publication — the free thread safety

A correctly constructed object whose fields are all final cannot be observed half-initialised by another thread. The JVM inserts a memory barrier at the end of the constructor — the final field freeze — guaranteeing that any thread which sees the reference sees fully initialised fields, with no synchronization at all. Mutable objects need an explicit happens-before edge (a volatile write, a lock, or a concurrent collection) to be published safely.

Interview angle

final on a field stops reassignment of the reference only. A private final List can still have elements added — immutability is about the whole reachable object graph, not the top-level field. That distinction is a very common follow-up.

Chapter 16

Records

A record (Java 16+) is a transparent carrier for data. The compiler generates a canonical constructor, accessor methods named after the components (id(), not getId()), and correct equals, hashCode and toString derived from all components. Records are implicitly final and cannot extend a class.

Java
record Point(int x, int y) {}

// equivalent to roughly 40 lines of constructor, accessors,
// equals, hashCode and toString - all correct by construction

What a record does not give you

Deep immutability. record Order(String id, List<Item> items) holds a reference to the caller's list, which they can still mutate. Use a compact constructor to validate and copy — it runs before the fields are assigned, and reassigning the parameter is the idiom.

Java
record Order(String id, List<Item> items) {
    Order {                                  // compact constructor
        Objects.requireNonNull(id);
        items = List.copyOf(items);          // reassign the PARAMETER
    }
    BigDecimal total() {                     // extra methods are fine
        return items.stream().map(Item::price)
                   .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}

When to use one

DTOs, API request and response types, value objects, method return types carrying several values, and the variants of a sealed hierarchy. Not for JPA entities — those need a no-argument constructor and mutable identity — and not for anything with meaningful behaviour beyond its data.

Interview angle

Records may declare static fields and extra constructors (which must delegate to the canonical one), but no additional instance fields. That restriction is what keeps them transparent: the components are the entire state, which is what makes the generated equals and hashCode trustworthy.

Chapter 17

Enums and sealed classes

Enums are more than constants

An enum is a fixed set of instances created by the JVM at class-initialization time. Because that initialization is lazy and guarded by the class-init lock, the enum singleton is the safest singleton in Java — thread-safe, lazily created, and uniquely immune to the two attacks that break other singletons, since the JVM forbids reflective enum construction and handles enum serialization specially.

Enums can carry state and even per-constant behaviour, which is the Strategy pattern with no boilerplate and compile-time exhaustiveness.

Java
enum Operation {
    PLUS("+")  { public long apply(long a, long b){ return a + b; } },
    TIMES("*") { public long apply(long a, long b){ return a * b; } };

    private final String symbol;
    Operation(String symbol){ this.symbol = symbol; }
    public abstract long apply(long a, long b);
}

enum Singleton { INSTANCE; }        // the safest singleton in Java

For collections of enums use EnumMap and EnumSet, not HashMap/HashSet — they are backed by an array and a bitmask respectively, so they are dramatically faster and smaller, and iterate in declaration order.

Sealed classes — a closed set with different shapes

A sealed interface or class names exactly which types may implement it. Each permitted subtype must itself be final, sealed, or explicitly non-sealed. The payoff is exhaustiveness: a switch expression covering every permitted subtype needs no default, and adding a variant later breaks the build at every such switch until it is handled.

Java
sealed interface PaymentResult permits Approved, Declined, Pending {}
record Approved(String authCode) implements PaymentResult {}
record Declined(String reason, boolean retryable) implements PaymentResult {}
record Pending(Instant checkAfter) implements PaymentResult {}

String describe(PaymentResult r) {
    return switch (r) {
        case Approved a -> "ok " + a.authCode();
        case Declined d when d.retryable() -> "retry: " + d.reason();
        case Declined d -> "final decline: " + d.reason();
        case Pending  p -> "check after " + p.checkAfter();
    };   // no default needed - adding a 4th variant breaks the build HERE
}
Interview angle

Enum when the variants are constants with the same shape; sealed hierarchy when each variant carries different data. An enum cannot give Approved an auth code and Declined a reason — that is exactly when you move to sealed records, and saying that distinction cleanly is a strong signal.

Chapter 18

Nested classes, and composition over inheritance

Four kinds of nested class

  • Static nested — a top-level class scoped inside another. No link to any outer instance.
  • Inner (non-static) — holds an implicit reference to its enclosing instance, so it can read the outer object's fields.
  • Anonymous — a one-off subclass or implementation declared inline.
  • Local — a named class declared inside a method.

That implicit reference is a real memory leak. The compiler adds a synthetic this$0 field pointing at the outer object, so if an inner-class instance outlives its outer object — stored in a static registry, handed to a long-lived listener, queued in an executor — the entire outer object and everything it references stays reachable.

Java
class Service {
    private byte[] cache = new byte[10_000_000];
    class Task implements Runnable { public void run(){} }         // holds Service.this
    static class SafeTask implements Runnable { public void run(){} } // holds nothing
}
// registry.add(service.new Task());   // pins the 10MB cache forever

The fix is almost always the keyword static. Lambdas behave better: a lambda only captures this if it actually references an instance member.

Composition over inheritance

Inheritance couples you to a superclass's internal call patterns. The canonical example: extend HashSet to count additions and you double-count, because addAll internally calls add — and a future JDK could change that silently. That is the fragile base class problem.

Java
class CountingSet<E> implements Set<E> {
    private final Set<E> delegate;            // composition
    private int addCount;
    public boolean add(E e){ addCount++; return delegate.add(e); }
    public boolean addAll(Collection<? extends E> c){
        addCount += c.size(); return delegate.addAll(c);   // no double count
    }
    // remaining methods forward to delegate
}

You now depend only on the published Set interface, not on how the implementation calls itself. This is the Decorator pattern.

Interview angle

The test for when inheritance is right is Liskov substitution: a subtype must be usable anywhere the supertype is without surprising the caller. Square extends Rectangle fails it — code that sets width and height independently and asserts the area breaks. Effective Java's rule: design and document for inheritance, or prohibit it with final.

III. The Core Libraries
Chapter 19

Strings, the pool and StringBuilder

String is immutable: the backing array is final and never handed out, so every apparent modification returns a new String. Four things follow, and they explain most String interview questions.

  • Thread safety for free — no synchronization is ever needed to share a String.
  • Cached hash — computed once and stored, so repeated map lookups are cheap.
  • Safe as a map key — the hash cannot change after insertion.
  • Security — a validated filename or URL cannot be altered between the check and the use.

The string pool

The pool is a JVM-managed table of canonical String instances. Literals are interned automatically at class load, so two identical literals are the same object — which is why == deceptively works for literals and fails for runtime-built strings. Since Java 7 the pool lives in the heap rather than PermGen, so heavy interning is a garbage-collection concern rather than a PermGen overflow.

Java
String a = "hello";
String b = "hello";
String c = new String("hello");
a == b;             // true  - same pooled literal
a == c;             // false - a distinct heap object
a == c.intern();    // true  - the canonical instance
a.equals(c);        // true  - the only comparison you should write

Building strings

Concatenation in a loop is O(n²): each += allocates a new String and copies everything so far. Use a StringBuilder, which keeps a growable buffer and appends in amortised O(1). StringBuffer is its synchronized legacy twin and is almost never needed.

Java
// O(n^2) - allocates and copies every iteration
String s = ""; for (String p : parts) s += p;

// O(n)
StringBuilder sb = new StringBuilder(parts.size() * 16);   // pre-size if known
for (String p : parts) sb.append(p);

String joined = String.join(", ", parts);      // idiomatic for the simple case

Note that a single expression like a + b + c is fine — since Java 9 the compiler turns it into an efficient invokedynamic concatenation that sizes the buffer in one pass. Only repetition across statements or loop iterations is quadratic.

Interview angle

Two extras worth having ready: compact strings (Java 9+) store Latin-1 text in a byte[] rather than always using char[], roughly halving memory for ASCII-heavy applications; and String.length() returns UTF-16 code units, so an emoji counts as 2 — use codePointCount when you mean characters.

Chapter 20

The collections framework, mapped

Two roots: Collection (List, Set, Queue/Deque) and Map, which is deliberately not a Collection because its elements are pairs rather than single values.

Hierarchy
Collection
  |- List    ordered, duplicates allowed, index access
  |     ArrayList | LinkedList | CopyOnWriteArrayList
  |- Set     unique membership
  |     HashSet | LinkedHashSet | TreeSet
  |- Queue / Deque   processing from the ends
        ArrayDeque | PriorityQueue | LinkedList | BlockingQueue family

Map        key -> value
     HashMap | LinkedHashMap | TreeMap | ConcurrentHashMap | EnumMap

Choose by access pattern

  • Index access → ArrayList
  • Membership tests → HashSet
  • Key lookup → HashMap
  • Insertion or access order → LinkedHashMap / LinkedHashSet
  • Sorted iteration or range queries → TreeMap / TreeSet
  • FIFO or LIFO → ArrayDeque
  • Priority ordering → PriorityQueue
  • Enum keys → EnumMap (array-backed, far faster)

Know the three implementation families for hashed types, because naming them signals fluency: Hash* (unordered, O(1)), Linked* (O(1) plus a linked list maintaining order), Tree* (sorted, O(log n)).

Views are live

Map exposes three views — keySet(), values(), entrySet() — and they are backed by the map, not copies. Removing from the key set removes from the map. That is useful and occasionally surprising.

Interview angle

For a stack, the answer is ArrayDeque, not Stack. The legacy Stack extends Vector, is synchronized on every operation, and iterates bottom-up — the wrong order. Deque's push/pop/peek is the modern answer, and mentioning why is a cheap way to show you know the library's history.

Chapter 21

ArrayList, LinkedList and ArrayDeque

ArrayList wraps an Object[]. Size is how many elements you have; capacity is how long the array is. When size reaches capacity it grows by roughly 50% (newCap = old + (old >> 1)), allocates a new array, and copies with System.arraycopy — an intrinsic the JIT turns into a fast bulk memory move.

So add at the end is amortised O(1), get is O(1), but insert or remove in the middle is O(n) because everything after shifts.

Java
List<String> l = new ArrayList<>(10_000);   // pre-size: one allocation, not ~20 grows

// accidental O(n^2) - each remove shifts the tail
for (int i = 0; i < list.size(); i++) if (bad(list.get(i))) list.remove(i--);

// O(n)
list.removeIf(this::bad);

Why LinkedList loses

On paper LinkedList wins for insertion and deletion at a known node. In practice it loses almost everywhere, because Big-O ignores cache locality. ArrayList's elements sit in one contiguous array, so the CPU prefetcher streams through them; LinkedList's nodes are scattered across the heap, so nearly every step is a cache miss — and each node costs an object header plus two pointers, roughly 24 extra bytes.

There is also a hidden cost: to insert "in the middle" you must first walk there, which is O(n) anyway. The O(1) advantage only materialises when you already hold an iterator at the spot.

ArrayDeque for queues and stacks

Java
Deque<Task> stack = new ArrayDeque<>();  stack.push(t); stack.pop();   // LIFO
Deque<Task> queue = new ArrayDeque<>();  queue.offer(t); queue.poll();  // FIFO

// ArrayDeque forbids null elements deliberately:
// poll() returning null then unambiguously means "empty"

A circular array with no per-element node objects, faster than both LinkedList and the legacy Stack.

Interview angle

The honest interview answer is "LinkedList is almost never the right choice; I would use ArrayList or ArrayDeque" — followed by the cache-locality reason. Reciting the Big-O table without that caveat is the mid-level answer; naming why the table misleads is the senior one.

Chapter 22

HashMap internals

This is the most examined data structure in Java interviews, and the details are worth knowing precisely.

A HashMap is an array of buckets. For a key it takes hashCode(), spreads it with h ^ (h >>> 16) so high bits influence the result, then indexes with h & (capacity - 1) — which works because capacity is always a power of two, making that mask equivalent to modulo but far cheaper.

Java
int index = (n - 1) & (h ^ (h >>> 16));    // spread, then mask

Collisions and treeification

Collisions chain in a linked list. Since Java 8, once one bucket reaches 8 nodes and the table has at least 64 buckets, that chain converts to a red-black tree, changing worst-case lookup from O(n) to O(log n). It converts back at 6 nodes — the gap between 8 and 6 is deliberate hysteresis so a map hovering at the boundary does not thrash.

Treeification was added as a defence against hash-collision denial of service, where an attacker sends keys engineered to land in one bucket. With a decent hash function the probability of 8 collisions in one bucket is vanishingly small, so the tree path should never trigger in normal operation.

Resizing

Resize triggers when size exceeds capacity × loadFactor. The default 0.75 is a measured balance: lower wastes memory, higher raises collision probability sharply. Capacity doubles — and because it doubles, each old bucket's entries split into exactly two destinations, the same index or that index plus the old capacity, decided by a single additional bit.

Java
int expected = 10_000;
Map<String,Order> m = new HashMap<>((int)(expected / 0.75f) + 1);  // avoid ~20 resizes

The Java 7 infinite loop

Java 7 reversed entry order during a resize, and under concurrent access two threads resizing simultaneously could create a cycle in a bucket's linked list — so a later get spun forever at 100% CPU. Java 8 preserves relative order during the split, which removes that particular failure. HashMap is still not thread-safe, and concurrent use can still lose entries.

Interview angle

The complete answer covers: spreading, power-of-two masking, chaining, treeify at 8 with capacity ≥ 64, untreeify at 6, load factor 0.75, and the split-into-two-destinations resize. If you can also name the Java 7 infinite loop and why Java 8 fixed it, you are past what most candidates offer.

Chapter 23

LinkedHashMap, TreeMap and PriorityQueue

LinkedHashMap — and a five-line LRU cache

A HashMap plus a doubly linked list threaded through the entries, so iteration has a predictable order at a small memory cost. The third constructor argument chooses the order: false is insertion order (default), true is access order, where every get or put moves the entry to the end.

Java
class LruCache<K,V> extends LinkedHashMap<K,V> {
    private final int max;
    LruCache(int max) { super(16, 0.75f, true); this.max = max; }   // access order
    @Override protected boolean removeEldestEntry(Map.Entry<K,V> e) { return size() > max; }
}

TreeMap — a red-black tree

A self-balancing binary search tree: get, put and remove are all O(log n) and iteration is in sorted key order. The reason to choose it over a HashMap is the NavigableMap API — floorKey, ceilingKey, headMap, tailMap, subMap, firstEntry. Range and nearest-neighbour queries are exactly what a hash map cannot do at any price.

Java
NavigableMap<Instant, Rate> rates = new TreeMap<>();
Rate inEffect = rates.floorEntry(when).getValue();      // "rate at or before `when`"
Map<Instant,Rate> window = rates.subMap(from, true, to, false);

Two gotchas: ordering comes from compareTo or the supplied Comparator, not from equals — so an inconsistent comparator silently merges distinct elements. And TreeMap rejects null keys, because it must compare them.

PriorityQueue — a binary min-heap

Stored in an array; the smallest element by the comparator is always at index 0. offer and poll are O(log n), peek is O(1), and building from a collection is O(n) via heapify.

The classic surprise: iteration and toString are not sorted. The heap only guarantees the parent-child invariant, not a total order in the array. The only sorted access is repeatedly polling.

Java
// K largest with a size-K MIN heap: O(n log k) time, O(k) space
PriorityQueue<Integer> heap = new PriorityQueue<>();       // natural = min-heap
for (int x : nums) { heap.offer(x); if (heap.size() > k) heap.poll(); }
// heap.peek() is now the kth largest
Interview angle

The top-K pattern above is worth memorising — it beats sorting the whole input whenever K is small, and it turns up constantly in both coding rounds and system design ("top 10 trending items").

Chapter 24

Iterators and comparators

Fail-fast iterators

Collections in java.util track a modCount. An iterator snapshots it and compares on every next(), throwing ConcurrentModificationException if the collection was structurally modified by anything other than the iterator itself.

Java
// throws ConcurrentModificationException
for (String s : list) if (s.isBlank()) list.remove(s);

// correct: remove through the iterator
Iterator<String> it = list.iterator();
while (it.hasNext()) if (it.next().isBlank()) it.remove();

// clearest
list.removeIf(String::isBlank);

Crucially this is a best-effort bug detector, not a guarantee: modCount is not volatile and the check is unsynchronized, so under real concurrency a modification may go unseen. It reliably catches the single-threaded mistake, which is what it exists for. Never write code that depends on catching it.

Fail-safe (weakly consistent) iterators — ConcurrentHashMap, CopyOnWriteArrayList — never throw. They either iterate an immutable snapshot or reflect some state at or after creation.

Composing comparators

Since Java 8, comparators compose declaratively instead of being hand-written. Use the primitive-specialised forms when the key is a primitive, to avoid boxing on every comparison inside a sort.

Java
Comparator<Employee> byDeptThenSalaryDesc =
    Comparator.comparing(Employee::dept)
              .thenComparing(Comparator.comparingInt(Employee::salary).reversed())
              .thenComparing(Employee::name);

list.sort(byDeptThenSalaryDesc);

Comparator<String> safe = Comparator.nullsFirst(Comparator.naturalOrder());
Interview angle

The most common comparator mistake is that reversed() applies to the entire chain built so far, not just the last key. If you only want the first key reversed, reverse that key's comparator inside comparing, as in the example above.

Chapter 25

Exceptions

Java splits exceptions into checked (the compiler forces you to handle or declare them) and unchecked (RuntimeException and its subclasses). Error — OutOfMemoryError, StackOverflowError — signals conditions you should not attempt to recover from.

Hierarchy
Throwable
  |- Error              do not catch: OutOfMemoryError, StackOverflowError
  |- Exception          CHECKED - compiler enforced
       |- RuntimeException   UNCHECKED - programming errors
             NullPointerException, IllegalArgumentException, IllegalStateException

The intended split is: checked for recoverable, caller-actionable conditions (a file missing, a remote call failing); unchecked for programming errors (a null argument, an illegal state). The honest position is that checked exceptions have fallen out of favour — they do not compose with lambdas and streams, and in practice they get wrapped or swallowed, which is worse than not having them.

Rules that matter in review

  • Never swallow. catch (Exception e) {} is how outages become invisible.
  • Always preserve the cause when wrapping: throw new RepositoryException(msg, e).
  • Never catch Exception broadly at a low level.
  • Never use exceptions for control flow — they are expensive and they hide intent.
  • Never let an internal message or stack trace reach a client.

try-with-resources

Closes every declared AutoCloseable in reverse declaration order, even on exception. The subtlety worth knowing: if the body throws and close() throws, the close exception is attached as a suppressed exception rather than replacing the original — retrievable via getSuppressed(). Before this existed, a failure in a finally-block close routinely masked the real cause.

Java
try (var conn = pool.getConnection();
     var stmt = conn.prepareStatement(SQL)) {      // stmt closed first
    return map(stmt.executeQuery());
} catch (SQLException e) {
    throw new RepositoryException("loading order " + id, e);   // cause preserved
}
Interview angle

For a service API, design the exception contract deliberately: a small hierarchy meaningful to callers (NotFoundException, ConflictException, ValidationException), each mapping to one HTTP status and one stable error code. Leaking SQLException upward means your persistence choice is part of your public API.

Chapter 26

Optional and handling absence

Optional exists to make "there might be no result" explicit in a method signature, so callers cannot forget. That is its whole purpose, and it defines its correct use: as a return type.

Java
Optional<User> findByEmail(String email);        // the signature is honest

String name = findByEmail(e)
        .map(User::name)
        .filter(n -> !n.isBlank())
        .orElse("anonymous");

User u = findByEmail(e).orElseThrow(() -> new NotFoundException(e));

The anti-patterns

  • Not as a field — it is not Serializable and adds an object per instance.
  • Not as a parameter — provide an overload instead; forcing callers to wrap arguments is worse than a null check.
  • Not as a collection element — an empty collection already means "nothing".
  • Never get() without isPresent() — use orElse, orElseGet, orElseThrow, map.

orElse versus orElseGet

This one is a real production performance bug that reads as correct code. orElse evaluates its argument eagerly, even when a value is present.

Java
User bad  = findByEmail(e).orElse(loadDefaultFromDb());        // hits the DB ALWAYS
User good = findByEmail(e).orElseGet(() -> loadDefaultFromDb()); // only on absence
Interview angle

Optional is not a general null replacement. For fields and parameters, the tools are still: validate at the boundary with Objects.requireNonNull, never return null for a collection (return an empty one), and document nullability. Optional's value is that it makes absence visible in the signature — using it elsewhere costs allocation for no clarity.

Chapter 27

Dates, times and money

Choosing the right java.time type

The old Date and Calendar are mutable, badly designed and effectively deprecated. java.time types are immutable and thread-safe. Choosing among them is a matter of what the value means.

java.time
Instant         a point on the global timeline, UTC. No zone.
LocalDate       a calendar date. No time, no zone.
LocalDateTime   a wall-clock reading. NO ZONE - not an instant.
ZonedDateTime   local time + a zone ID -> applies DST rules
OffsetDateTime  local time + a fixed offset -> no DST rules
Duration        exact elapsed time (seconds/nanos)
Period          calendar amount (years/months/days)
  • A database timestamp / event log → Instant, stored as UTC.
  • A future meeting → ZonedDateTime, storing the local time and the zone ID — not an instant. If you store the instant, a government changing DST rules moves the meeting; the intent was "9am in Asia/Kolkata".
  • A birthday → LocalDate. Someone born on 14 March was born on 14 March everywhere.
  • Time between two instants → Duration; "one month later" → Period.

Also: SimpleDateFormat is mutable and not thread-safe — a static instance shared across threads produces corrupted output under load. DateTimeFormatter is immutable and safe.

Money

Never double. Use BigDecimal or an integer count of minor units (paise, cents). With BigDecimal there are three rules:

Java
new BigDecimal(0.1);      // 0.1000000000000000055511151231257827... - the double ctor
new BigDecimal("0.1");    // exactly 0.1  <- use the String form or valueOf

total.divide(new BigDecimal(3), 2, RoundingMode.HALF_UP);   // scale + mode REQUIRED
                                       // else a non-terminating result throws

new BigDecimal("2.0").equals(new BigDecimal("2.00"));    // false - scale differs
new BigDecimal("2.0").compareTo(new BigDecimal("2.00")); // 0 - equal in VALUE
Interview angle

A favourite follow-up: how do you split 100.00 three ways without losing a paisa? Round each share down, then distribute the remainder one minor unit at a time. Rounding each share independently and summing gives 99.99 — which reconciliation will catch and an auditor will ask about.

Chapter 28

IO, NIO and character encoding

Classic java.io is stream-based and blocking, built by composition — you wrap a raw stream in a buffer, then a reader, then a decoder. That is the Decorator pattern, and java.io is the canonical JDK example of it.

Buffering matters enormously. An unbuffered FileInputStream issues a syscall per byte. Wrapping it in a BufferedInputStream can be orders of magnitude faster.

Prefer java.nio.file for everyday work

Java
try (var reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
     var writer = Files.newBufferedWriter(out, StandardCharsets.UTF_8)) {
    String line;
    while ((line = reader.readLine()) != null) writer.write(transform(line));
}

// streaming a huge file without loading it into memory
try (Stream<String> lines = Files.lines(path)) {      // MUST be closed - holds a handle
    long errors = lines.filter(l -> l.contains("ERROR")).count();
}

Files.lines is both a Stream and AutoCloseable. Forgetting the try-with-resources leaks file descriptors until the process hits its limit — surfacing as a mysterious "too many open files" hours later.

Character encoding

A String in memory is Unicode; bytes on disk are an encoding of it. Every conversion needs a charset, and if you do not name one Java uses a platform default that differs between your laptop, CI and the production container — which is exactly how the same code produces correct output locally and mojibake in production.

Java
byte[] b = s.getBytes(StandardCharsets.UTF_8);   // never s.getBytes()
String back = new String(b, StandardCharsets.UTF_8);

Java 18 changed the default file encoding to UTF-8, which helps, but explicit is still correct and portable across versions. Watch for the implicit default hiding in new FileReader(f), new String(bytes) and PrintWriter.

Interview angle

NIO's non-blocking selector model genuinely helps only with many thousands of mostly idle connections. For ordinary request/response services, thread-per-request is simpler — and with virtual threads (Chapter 45) it is now also fast, which removes most of the historical reason to reach for NIO directly.

IV. Generics and Functional Java
Chapter 29

Generics and type erasure

Generics give compile-time type safety and remove casts. Before them, List held Object and every read needed a cast that could fail at runtime; List<String> moves that failure to compile time.

A bounded type parameter constrains what T can be, which is what lets you call methods on it. Bounds can be multiple — a class first, then interfaces.

Java
static <T extends Comparable<T>> T max(List<T> list) {
    T best = list.get(0);
    for (T t : list) if (t.compareTo(best) > 0) best = t;   // legal because of the bound
    return best;
}

static <T extends Number & Comparable<T>> void check(T t) {}   // multiple bounds

Erasure — and everything it breaks

Generics are implemented by erasure: the compiler checks types, then erases them, replacing T with its bound (Object if unbounded) and inserting casts. At runtime List<String> and List<Integer> are the same class. This was a compatibility decision — in 2004 the entire Java ecosystem was non-generic, and reification would have required an incompatible runtime.

Java
// none of these compile - the type is gone at runtime
// T instance = new T();
// T[] arr = new T[10];
// if (list instanceof List<String>) {}
// void f(List<String> l) {}  void f(List<Integer> l) {}   // same erasure!

// the standard workaround: pass the Class token
static <T> T create(Class<T> type) throws Exception {
    return type.getDeclaredConstructor().newInstance();
}

Static fields are also shared across all parameterisations, and bridge methods are synthesised by the compiler so that covariant overriding still works after erasure.

Interview angle

A good follow-up is how do Jackson and Spring read generic types at runtime if they are erased? With a super type token: an anonymous subclass captures the type argument in its class file (new TypeReference<List<Order>>(){}), and reflection reads it from the generic superclass signature. Generic information survives in class metadata — it is only absent from instances.

Chapter 30

Wildcards and PECS

Generics are invariant: List<String> is not a List<Object>, even though String is an Object. That is deliberate — it closes the hole that array covariance leaves open.

Java
Object[] objs = new String[2];    // legal: arrays ARE covariant
objs[0] = 42;                     // ArrayStoreException at RUNTIME

// List<Object> l = new ArrayList<String>();   // will not COMPILE - invariant

Wildcards restore the flexibility safely. ? extends T is a producer: you can read T out of it, but cannot write anything in (except null), because the compiler does not know the exact subtype. ? super T is a consumer: you can write T into it, but reads come back as Object.

That is PECS — Producer Extends, Consumer Super.

Java
// src produces T (read only); dst consumes T (write only)
static <T> void copy(List<? extends T> src, List<? super T> dst) {
    for (T t : src) dst.add(t);
}
copy(List.of(1, 2, 3), new ArrayList<Number>());   // only compiles because of PECS

List<? extends Number> producer = List.of(1, 2);
// producer.add(3);       // illegal - could be a List<Double>
Number n = producer.get(0);  // fine

The API design rule

Wildcards belong in parameters, never in return types. A wildcard in a return type propagates into every caller's variable declarations and infects their code with wildcards they cannot get rid of. Accept the widest type you can consume; return the narrowest useful type.

Interview angle

Related: a generic varargs parameter T... args secretly creates a T[], which erasure cannot make safe — that is heap pollution, and it is why such methods warn. @SafeVarargs suppresses the warning and is a promise that the method only reads from the array and never stores or leaks it.

Chapter 31

Lambdas and functional interfaces

A functional interface has exactly one abstract method, so a lambda can implement it. @FunctionalInterface is optional but makes the intent explicit and fails the build if someone adds a second abstract method.

java.util.function
Function<T,R>      apply    - transform
Supplier<T>        get      - produce, no input
Consumer<T>        accept   - consume, no output
Predicate<T>       test     - boolean
BiFunction<T,U,R>           - two arguments
UnaryOperator<T>            - Function<T,T>
BinaryOperator<T>           - BiFunction<T,T,T>

// primitive specialisations exist to avoid boxing in hot pipelines:
IntPredicate | ToIntFunction<T> | IntUnaryOperator | IntSupplier

Lambdas are not anonymous classes

A lambda compiles to an invokedynamic call site backed by LambdaMetafactory, which spins up the implementing class at runtime. The consequences are concrete: no class file per lambda, a non-capturing lambda is a singleton reused on every call, and the JIT can inline through the linked call site readily. An anonymous class, by contrast, produces a real Outer$1.class, a new instance per evaluation, and — if non-static — an implicit reference to the enclosing instance.

Also, this inside a lambda refers to the enclosing instance, not to the lambda. In an anonymous class it refers to the anonymous instance.

The effectively-final rule

A lambda captures values, not variables — the value is copied into the lambda instance. Allowing reassignment would create two diverging copies with no defined semantics, so the compiler requires captured locals to be final or effectively final. Fields are exempt, because they are reached through the captured this.

Java
int factor = 2;
List<Integer> doubled = nums.stream().map(n -> n * factor).toList();
// factor++;   // adding this breaks the lambda above

// method references - the four kinds
Function<String,Integer> parse   = Integer::parseInt;    // static
Consumer<String>         print   = System.out::println;  // bound instance
Function<String,String>   upper   = String::toUpperCase;  // UNBOUND instance
Supplier<List<String>>    factory = ArrayList::new;       // constructor
Interview angle

The distinction people fumble is bound versus unbound: String::length is a Function<String,Integer> — the string becomes the argument — while someString::length is a Supplier<Integer>, because the receiver is fixed. Being able to state that cleanly is a small but reliable signal.

Chapter 32

Streams

A stream pipeline has three parts: a source, zero or more intermediate operations, and one terminal operation. Intermediate operations are lazy — they build a description and do nothing. Only the terminal operation triggers execution.

Execution is then fused: elements flow through the whole chain one at a time, rather than each stage materialising a full intermediate collection. That is why filter().map().findFirst() can stop after examining a single element, and why putting filter before map matters — the expensive stage then sees fewer elements.

Java
// nothing runs - no terminal operation
Stream<Order> s = orders.stream().filter(Order::isPaid);

// fused and short-circuiting: enrich runs only until the first match
orders.stream().filter(Order::isPaid).map(this::enrich).findFirst();

// infinite source, bounded by a short-circuiting op
Stream.iterate(1, n -> n * 2).limit(10).forEach(System.out::println);

Stateless versus stateful operations

filter, map and peek are stateless — they hold nothing between elements and fuse perfectly. sorted and distinct are stateful full barriers: sorting must see every element before emitting the first, so laziness stops there and memory grows to the size of the stream.

Java
// sorts everything to take 10
orders.stream().sorted(byTotalDesc).limit(10).toList();

// O(n log 10), bounded memory
PriorityQueue<Order> heap = new PriorityQueue<>(comparing(Order::total));
for (Order o : orders) { heap.offer(o); if (heap.size() > 10) heap.poll(); }

Parallel streams — usually the wrong answer

parallelStream() splits work across the common ForkJoinPool, which is sized to cores−1 and shared by the entire JVM. It helps when the source splits cheaply (array, ArrayList, IntStream range), N is large, and the per-element work is CPU-bound. It hurts when N is small, when the source splits poorly (LinkedList, Files.lines, iterators), and catastrophically when the work blocks — one slow IO call occupies a common-pool thread and starves every other parallel stream in the process, including framework internals.

Interview angle

Two more facts worth having: a stream is single-use (consuming it twice throws IllegalStateException), and peek is specified for debugging only — implementations may skip it when a result can be computed without traversing every element, so using it for side effects makes behaviour version-dependent.

Chapter 33

Collectors

Collectors is where most real stream work happens, and the highest-value idiom is groupingBy with a downstream collector — the second argument transforms each group rather than just collecting it to a list.

Java
Map<String, Long> countByDept = employees.stream()
        .collect(groupingBy(Employee::dept, counting()));

Map<String, List<String>> namesByDept = employees.stream()
        .collect(groupingBy(Employee::dept, mapping(Employee::name, toList())));

// one pass, two aggregates (Java 12+)
var summary = employees.stream().collect(teeing(
        counting(), summingInt(Employee::salary), Summary::new));

toMap has two sharp edges

It throws IllegalStateException on a duplicate key unless you supply a merge function — and real data has duplicates. And unlike HashMap it throws NullPointerException on a null value, because its implementation uses Map.merge, which treats null as absent and so cannot represent it unambiguously.

Java
Map<String, Employee> byEmail = employees.stream()
        .collect(toMap(Employee::email, e -> e, (a, b) -> a));   // merge fn required

// four-arg form controls the map implementation
.collect(toMap(k, v, merge, TreeMap::new));

Writing a custom Collector

Five parts: supplier (fresh mutable container), accumulator (fold one element in), combiner (merge two containers), finisher (transform to the result), and characteristics.

Java
Collector<Order, StringJoiner, String> ids = Collector.of(
    () -> new StringJoiner(", ", "[", "]"),   // supplier
    (j, o) -> j.add(o.id()),                   // accumulator
    StringJoiner::merge,                       // combiner - PARALLEL ONLY
    StringJoiner::toString);                   // finisher
Interview angle

The trap is the combiner: it is never called in a sequential stream, so a wrong combiner passes every test and silently corrupts results the day someone adds .parallel(). If you cannot write a correct one, say the collector is sequential-only rather than leaving a landmine.

V. Concurrency
Chapter 34

Threads, and why cancellation is cooperative

A thread moves through NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED. RUNNABLE in Java covers both "running" and "ready to run" — the JVM does not distinguish. BLOCKED means waiting for a monitor lock; WAITING means parked in wait(), join() or LockSupport.park().

Runnable returns nothing and cannot throw a checked exception; Callable<V> returns a value and may throw. Submit a Callable to an executor and you get a Future<V> — and note that an exception thrown inside is captured and only rethrown, wrapped in ExecutionException, when you call get(). A Future you never get() swallows failures silently.

Interruption

t.interrupt() only sets a flag. It does not stop anything. Blocking methods that declare InterruptedException throw it and clear the flag. So if you catch it and cannot propagate, you must restore it — otherwise the cancellation signal is lost and the thread keeps working.

Java
while (!Thread.currentThread().isInterrupted()) {
    try {
        queue.take();                        // throws InterruptedException, CLEARS the flag
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();  // restore it, then exit
        break;
    }
}

// never do this - it swallows cancellation entirely
// catch (InterruptedException e) { }
Interview angle

Thread.stop() was deprecated because it threw an asynchronous exception at an arbitrary bytecode, leaving objects half-updated and monitors released with broken invariants. There is no safe way to force-stop a thread — cancellation must be cooperative, which is exactly why the interrupt flag exists and why restoring it matters.

Chapter 35

synchronized and intrinsic locks

Every Java object has an intrinsic lock (a monitor). synchronized on an instance method locks this; on a static method it locks the Class object; a synchronized(obj) block locks whatever you name.

Those are different locks — a common bug is assuming a static and an instance synchronized method exclude each other. They do not.

Intrinsic locks are reentrant: the owning thread can re-acquire the same lock (a counter is incremented), which is what allows a synchronized method to call another synchronized method on the same object without deadlocking against itself. Without reentrancy, composition would be impossible.

Java
class Counter {
    private final Object lock = new Object();      // private lock, not `this`
    private int count;
    void inc() { synchronized (lock) { count++; } }

    synchronized void a() { b(); }   // reentrant: b() re-acquires the same monitor
    synchronized void b() { }
}

Lock on a private final object

Locking on this or on a public field makes your lock part of your public API — any caller can synchronize on your object and interfere with you, and you can never change the strategy. And never lock on a String literal or a boxed Integer: they are pooled and shared JVM-wide, so unrelated code can contend with you.

What synchronized gives you besides exclusion

Visibility. Releasing a monitor flushes writes and acquiring it invalidates cached reads, establishing a happens-before edge (Chapter 36). Mutual exclusion without that memory guarantee would be useless — and this is why "just make it atomic" is not the whole story.

Interview angle

Is synchronized slow? Not usually — the JVM optimises uncontended locks heavily. Contention is what costs, and that is a design problem (lock scope, lock granularity), not a keyword problem. The right first response to a lock bottleneck is to shrink the critical section, not to swap the mechanism.

Chapter 36

The Java Memory Model

The JMM defines when a write by one thread is guaranteed visible to a read by another. Without it, the compiler, the JIT and the CPU are all free to reorder and cache — and they do. The JMM is not about locks; it is about which reorderings are legal.

The central relation is happens-before. If action A happens-before action B, A's effects are visible to B. The edges you must be able to list:

  • Program order within a single thread.
  • Monitor unlock → subsequent lock of the same monitor.
  • Volatile write → subsequent volatile read of the same field.
  • Thread.start() → everything in that thread.
  • Everything in a thread → another thread's successful join().
  • The final field freeze at the end of a constructor → publication of the reference.

The part most people miss: without an edge there is no guarantee at all — not "eventually", not "probably within milliseconds". A loop reading a non-volatile flag can be hoisted out by the JIT and spin forever.

Java
// broken: no happens-before edge, may never terminate
boolean running = true;
// thread A:  while (running) { }     // JIT may hoist the read OUT of the loop
// thread B:  running = false;

volatile boolean running = true;      // fixed - creates the edge

volatile: visibility and ordering, not atomicity

volatile guarantees the write is pushed out and the read is not served from a cached copy, and it forbids reordering across the access. What it does not give is atomicity of compound operations. i++ is read-modify-write — three steps — so two threads can both read 5, both write 6, and one increment vanishes.

Java
volatile int count;
count++;                          // STILL a race
new AtomicInteger().incrementAndGet();   // correct
Interview angle

Use volatile for a flag or a reference that one thread writes and others read — a shutdown signal, a swapped-in configuration object. For counters use AtomicInteger or LongAdder; for several fields that must move together, use a lock. And note this is why "it works on my machine" is meaningless for concurrency: x86 has strong ordering and hides bugs that appear immediately on ARM.

Chapter 37

Atomics, CAS and safe publication

Compare-and-swap is a single CPU instruction: "if this memory location still holds the value I expect, replace it — atomically". AtomicInteger.incrementAndGet is a loop around it: read, compute, CAS; if the CAS fails because someone else won the race, read again and retry.

Java
int current;
do { current = value.get(); } while (!value.compareAndSet(current, current + 1));

// the general form - the function may run MORE THAN ONCE, so keep it pure
AtomicReference<Config> ref = new AtomicReference<>(initial);
ref.updateAndGet(c -> c.withRetries(c.retries() + 1));

That is optimistic concurrency: no locking, no context switch. It wins at low-to-moderate contention. Under heavy contention it loses — threads spin, burning CPU while making no progress, and a lock that parks the thread can be faster. A CAS loop is lock-free but not wait-free: the system always progresses, but an individual thread can starve.

The ABA problem

A CAS checks the value, not the history. If another thread changes A→B→A, your CAS succeeds even though the world changed underneath. It rarely matters for counters, but it breaks lock-free stacks where a node was popped, freed and recycled at the same address. AtomicStampedReference pairs the value with a version counter.

LongAdder versus AtomicLong

Under heavy write contention every thread CASes the same memory word, so cache lines ping-pong between cores and most attempts fail. LongAdder stripes — a base value plus per-thread cells — so writes rarely collide; sum() then adds the cells, making reads more expensive and non-atomic.

Java
LongAdder requests = new LongAdder();   // write-heavy metric
requests.increment();  long total = requests.sum();   // eventually consistent

AtomicLong sequence = new AtomicLong();  // need an exact, immediately-readable value
long next = sequence.incrementAndGet();

Safe publication and double-checked locking

Double-checked locking was broken before Java 5 and is correct now only if the field is volatile. instance = new Registry() is allocate, construct, assign — and the JIT may reorder assign before construct, so another thread sees a non-null reference to a half-built object.

Java
class Registry {
    private static volatile Registry instance;      // volatile is MANDATORY
    static Registry get() {
        Registry r = instance;
        if (r == null) synchronized (Registry.class) {
            r = instance;
            if (r == null) instance = r = new Registry();
        }
        return r;
    }
}

// simpler and preferred - the JVM's class-init lock does the work
class Registry2 {
    private static class H { static final Registry2 I = new Registry2(); }
    static Registry2 get(){ return H.I; }
}
Interview angle

Underneath all of this is false sharing — two variables written by different cores landing on the same 64-byte cache line, so each write invalidates the other core's copy even though the variables are unrelated. That is what LongAdder's padded cells and @Contended exist to avoid.

Chapter 38

Explicit locks and conditions

ReentrantLock does everything synchronized does, plus the things it cannot.

  • tryLock() — give up immediately rather than block.
  • tryLock(timeout) — the standard deadlock escape.
  • lockInterruptibly() — cancellable acquisition.
  • Optional fairness (FIFO handoff).
  • Multiple Conditions on one lock.
  • Acquire in one method, release in another.

The cost is that you must unlock() in a finally — forget it and the lock leaks permanently.

Java
if (lock.tryLock(200, TimeUnit.MILLISECONDS)) {
    try { doWork(); } finally { lock.unlock(); }   // finally is MANDATORY
} else {
    metrics.lockTimeout();          // back off instead of blocking forever
}

Conditions beat wait/notify

With a single monitor, all waiters share one wait set, so notify() may wake a producer when you needed a consumer — the classic missed signal that stalls a queue with work available. notifyAll avoids it by waking everyone to re-check, at the cost of a thundering herd. Two Conditions solve it precisely.

Java
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull  = lock.newCondition();
private final Condition notEmpty = lock.newCondition();

void put(E e) throws InterruptedException {
    lock.lock();
    try {
        while (count == items.length) notFull.await();   // WHILE, never if
        enqueue(e);
        notEmpty.signal();                                // wake a consumer only
    } finally { lock.unlock(); }
}

Always wait in a while loop, never an if: spurious wakeups are permitted by the specification, and even without them another thread can win the lock after the signal and consume the item, so the predicate must be re-checked.

ReadWriteLock and StampedLock

ReadWriteLock allows many readers or one writer, but it has higher acquisition overhead and risks writer starvation — it only pays off when reads are long and writes are rare. StampedLock adds optimistic reads: take a stamp, read without locking, then validate; if a write intervened, fall back to a real read lock. Dramatically cheaper, but it is not reentrant and you must copy fields into locals inside the optimistic block.

Interview angle

The honest default is prefer synchronized — harder to misuse, reads better, performs comparably. Reach for ReentrantLock only when you need one of the capabilities above. Fairness in particular roughly halves throughput, so use it only when starvation is a measured problem.

Chapter 39

Executors and thread pools

A ThreadPoolExecutor is defined by six things — corePoolSize, maximumPoolSize, keepAliveTime, the work queue, a thread factory and a rejection policy — and the interaction between them is counter-intuitive, which is exactly what gets asked.

The submission algorithm

Order
1. fewer than CORE threads?        -> create a new thread
2. otherwise                      -> try to QUEUE the task
3. queue FULL?                    -> create threads up to MAXIMUM
4. queue full AND at maximum?     -> REJECT (rejection policy)

The consequence is the trap: with an unbounded queue the queue never fills, so step 3 never happens and maximumPoolSize is never reached. The pool silently stays at core size while the queue grows until you run out of heap. That is exactly what Executors.newFixedThreadPool and newSingleThreadExecutor do — which is why the advice is to construct ThreadPoolExecutor directly with a bounded queue.

Java
ExecutorService pool = new ThreadPoolExecutor(
        8, 16, 60, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(1000),                    // BOUNDED
        new ThreadFactoryBuilder().setNameFormat("orders-%d").build(),
        new ThreadPoolExecutor.CallerRunsPolicy());        // backpressure

pool.shutdown();
if (!pool.awaitTermination(30, SECONDS)) pool.shutdownNow();

Rejection policies

AbortPolicy throws (the default, and usually correct — a visible signal). CallerRunsPolicy executes the task on the submitting thread, which is elegant backpressure because it slows the producer down. DiscardPolicy and DiscardOldestPolicy lose work silently and are rarely right.

Sizing

CPU-bound ≈ availableProcessors(), sometimes +1. IO-bound ≈ cores × (1 + waitTime/serviceTime). But the systems-level point matters more: the pool is not the only limit — 200 threads in front of a 20-connection database pool just moves the queue. Size the whole chain together.

Interview angle

Always name your threads. A thread dump with two hundred threads called pool-3-thread-17 is unreadable; named pools turn a production stack dump into an immediate diagnosis. And use a separate pool per dependency — that is the bulkhead pattern, and it stops one slow downstream exhausting the threads your health check needs.

Chapter 40

CompletableFuture

CompletableFuture composes asynchronous steps without blocking a thread on get(). The vocabulary is small: thenApply transforms a value, thenCompose flattens a nested future (the async flatMap), thenCombine joins two independent futures, and allOf/anyOf fan in.

Java
CompletableFuture.supplyAsync(() -> userClient.fetch(id), ioPool)
    .thenCompose(u -> CompletableFuture
            .supplyAsync(() -> prefsClient.fetch(u.id()), ioPool)
            .thenApply(prefs -> new Profile(u, prefs)))
    .orTimeout(2, TimeUnit.SECONDS)
    .exceptionally(ex -> { log.warn("degraded", ex); return Profile.empty(); });

Two rules that are not optional

Always pass an explicit executor. The no-argument *Async methods use the shared common ForkJoinPool — sized to cores−1 and used JVM-wide — so one blocking call inside starves everything else, including framework internals you did not write.

Always terminate the chain with something exception-aware. An exception completes the future exceptionally and short-circuits the dependent chain: thenApply stages are skipped. If nothing ever joins or handles it, the exception simply vanishes — no stack trace, no log. Unlike an uncaught exception in a thread, there is no default handler.

The three handlers

  • exceptionally(fn) — runs only on failure, lets you recover with a fallback value.
  • handle(fn) — runs on both outcomes with (value, throwable), one of them null; can recover and transform.
  • whenComplete(fn) — runs on both but is a side-effect stage: it cannot change the result. Use it for logging and metrics.
Interview angle

Exceptions arrive wrapped in CompletionException (or ExecutionException from get), so handlers must call getCause() to inspect the real type — a very common source of instanceof checks that mysteriously never match. Also note allOf fails if any future fails but does not cancel the others, which is precisely the gap structured concurrency closes.

Chapter 41

Concurrent collections

ConcurrentHashMap

Java 8 rewrote it. The old segment/lock-striping design is gone; it is now a single table where a write CASes the first node into an empty bin and takes a synchronized lock on that bin's head node only when a chain already exists. Lock granularity is per-bucket, and reads are entirely lock-free — get never blocks.

size() is an estimate, summed from a base counter plus striped cells without locking. Iterators are weakly consistent: they never throw ConcurrentModificationException, traverse elements as of some point at or after creation, and never return an element twice.

The API point that catches people: individual methods are atomic, but a sequence of them is not.

Java
// NOT atomic - two threads can both pass the check
// if (!m.containsKey(k)) m.put(k, v);

// atomic, and the value function runs at most once per absent key
m.computeIfAbsent(key, k -> new CopyOnWriteArrayList<>()).add(order);
m.merge(key, 1L, Long::sum);        // atomic counter increment

CHM also forbids null keys and values, deliberately: get(k) == null would be ambiguous under concurrency — absent, or present-with-null? — and you could not disambiguate with containsKey because the answer might change between the calls.

CopyOnWriteArrayList

Every mutation copies the entire backing array, so reads are lock-free and iteration works on an immutable snapshot. Writes are O(n) and allocation-heavy, so it is correct only for read-dominant, small collections — listener registries, cached configuration, routing tables that change on deploy.

Java
private final List<EventListener> listeners = new CopyOnWriteArrayList<>();
for (EventListener l : listeners) l.on(e);   // no lock, no CME, safe even if a
                                             // listener unregisters mid-iteration

BlockingQueue

The backbone of producer-consumer designs: put blocks when full, take blocks when empty, so flow control is built in. ArrayBlockingQueue is bounded and array-backed; LinkedBlockingQueue is unbounded by default (the OOM trap); SynchronousQueue has capacity zero and is a direct handoff; DelayQueue releases elements only after their delay expires.

Interview angle

The danger inside computeIfAbsent is that the mapping function runs while the bin is locked. Recursively updating the same map can deadlock or corrupt it — the JDK detects some cases and throws IllegalStateException. Keep the function short and free of callbacks into the map.

Chapter 42

Deadlock, coordination and diagnosis

Deadlock requires four conditions simultaneously: mutual exclusion, hold-and-wait, no preemption, and circular wait. Break any one and it cannot happen — that framing turns "add a timeout" into a reasoned answer.

Java
// deadlocks when called as transfer(x,y) and transfer(y,x) concurrently
void transfer(Account a, Account b, long amt) {
    synchronized (a) { synchronized (b) { a.debit(amt); b.credit(amt); } }
}

// FIX 1 - global lock ordering: breaks CIRCULAR WAIT (the best fix)
void transferSafe(Account a, Account b, long amt) {
    Account first  = a.id() < b.id() ? a : b;
    Account second = a.id() < b.id() ? b : a;
    synchronized (first) { synchronized (second) { a.debit(amt); b.credit(amt); } }
}

// FIX 2 - tryLock with randomized backoff: breaks HOLD-AND-WAIT
// FIX 3 - remove the need for two locks at all

Fix 1 is best because it eliminates the possibility rather than recovering from it. Handle equal ids with System.identityHashCode, and if those collide too, take a third tie-breaker lock first — the standard three-step scheme.

Detection in production

jstack <pid> or jcmd <pid> Thread.print prints "Found one Java-level deadlock" with both stacks and the lock identities — it is genuinely that explicit. Programmatically, ThreadMXBean.findDeadlockedThreads() can back a health check. The symptom that leads you there is threads in BLOCKED state that never move across three dumps taken seconds apart, with flat CPU.

Livelock is threads actively responding to each other and making no progress — CPU is high, unlike deadlock. Randomized backoff is the cure. Starvation is a thread never getting the resource, typically under an unfair lock.

Coordination primitives

  • CountDownLatch — one-shot, asymmetric: waiters wait for N events. Cannot be reset.
  • CyclicBarrier — reusable, symmetric: the same N threads rendezvous repeatedly.
  • Semaphore — bounds concurrent access with permits. The standard way to cap load on a fragile downstream.
  • Phaser — a barrier with dynamic party registration. Rarely needed.
  • CompletableFuture.allOf — for async composition; prefer it to a latch when the work is already asynchronous, because a latch blocks a thread purely to wait.
Interview angle

The general rule that avoids most real deadlocks: never call foreign or blocking code while holding a lock, and keep lock scopes as small as possible. Almost every production deadlock involves a lock held across a call into code the author did not control.

Chapter 43

Virtual threads

A virtual thread (Java 21+, JEP 444) is a lightweight thread managed by the JVM, not the OS. Millions can exist; each is a heap object with a growable stack, mounted onto a small pool of OS carrier threads only while running. When it blocks on IO it unmounts, freeing the carrier — so blocking stops being expensive.

What changes practically: thread-per-request becomes viable again for IO-bound services, with ordinary readable code, real stack traces and working debuggers, at throughput comparable to reactive frameworks.

Java
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
    for (var req : requests) exec.submit(() -> handle(req));   // millions is fine
}

What does not change, and the three pitfalls

Virtual threads give you no extra CPU, so CPU-bound work still needs a bounded pool sized to cores.

  • Do not pool them. They are cheap to create; pooling defeats the point. Use newVirtualThreadPerTaskExecutor.
  • Pinning. A virtual thread blocking inside a synchronized block or a native frame cannot unmount and holds its carrier. Recent JDKs largely fixed the synchronized case, but ReentrantLock is the safe pattern in blocking code.
  • Concurrency is now unbounded, so the thread pool no longer limits load on your dependencies. You must add that limit explicitly — a Semaphore in front of the database — or you simply move the collapse one layer down.
Java
// the pool used to be your implicit concurrency limit. Now make it explicit:
Semaphore db = new Semaphore(50);

// pinning risk
// synchronized (lock) { httpClient.send(...); }   // avoid
ReentrantLock lock = new ReentrantLock();          // prefer - unmounts correctly

// detect pinning:  -Djdk.tracePinnedThreads=full

Structured concurrency

The companion feature: subtasks forked inside a scope must all complete before the scope exits. If one fails the others are automatically cancelled, nothing outlives the scope, and the relationships are visible in the stack trace — none of which allOf gives you.

Interview angle

The question this always leads to is does Loom remove the need for reactive programming? For most request/response services, yes — it removes the main motivation, which was thread efficiency, and it restores debuggability. Reactive still earns its place for streaming with explicit backpressure and complex event composition.

VI. Inside the JVM
Chapter 44

Class loading

Classes are loaded by a hierarchy: bootstrap (core JDK) → platform (JDK modules) → application (your classpath). The delegation model means each loader asks its parent first, loading the class itself only if the parent cannot. That is what stops you replacing java.lang.String with your own, and it is the security foundation of the whole model.

Class identity is (name, loader), not name alone. So the same class name loaded by two loaders produces two distinct runtime classes, and casting between them throws a ClassCastException that reads like nonsense — "cannot cast Foo to Foo". Application servers and plugin systems invert delegation (child-first) so each deployment can carry its own library versions, which is where most classloader pain comes from.

Linking and initialization

After loading comes verification (the bytecode verifier proves type safety and that no instruction jumps somewhere illegal — this is why the JVM can run untrusted bytecode), preparation (static fields get default values, not their initialisers), and lazy resolution of symbolic references.

Then initialization runs the static initialisers — exactly once, lazily, on first active use, guarded by a per-class lock. That guarantee is what the holder idiom exploits for a lazy singleton with no synchronization in your code.

Java
class Config {
    private Config() {}
    private static class Holder { static final Config INSTANCE = new Config(); }
    static Config get() { return Holder.INSTANCE; }   // lazy + thread-safe, no locks
}

class A { static final int X = 42; }
// int y = A.X;   does NOT initialise A - javac inlines the compile-time constant

Classloader leaks

The classic redeploy problem: something with a longer lifetime than the app — a static field in a parent-loaded class, a running thread, a ThreadLocal, a registered JDBC driver, a shutdown hook — holds a reference into the app's loader. That pins the loader and every class it loaded. It shows as Metaspace growth across redeploys, not heap growth.

Interview angle

If a static initializer throws, the class is marked erroneous and every later use throws NoClassDefFoundError — with the original ExceptionInInitializerError visible only in the first stack trace. In production that means the real cause is in a log line from hours earlier, which makes it a notoriously confusing diagnosis.

Chapter 45

Memory areas and object layout

The runtime data areas, and the operational point that follows from them:

JVM memory
heap        all objects, GC-managed, shared      -> -Xmx
Metaspace   class metadata, NATIVE memory          -> unbounded by default
stacks      one per thread, ~1MB reserved each     -> -Xss
code cache  JIT-compiled native code
direct      NIO ByteBuffers, native libraries      -> -XX:MaxDirectMemorySize

Heap is not the process footprint. Total RSS ≈ heap + Metaspace + thread stacks + code cache + direct buffers + GC structures. Setting -Xmx equal to the container limit is therefore a reliable way to get OOMKilled while the heap graph looks perfectly healthy — you left nothing for everything else.

Shell
# container baseline - leave room for non-heap
-XX:MaxRAMPercentage=70
-XX:MaxMetaspaceSize=256m
-XX:MaxDirectMemorySize=256m

# see the real breakdown
java -XX:NativeMemoryTracking=summary ...
jcmd <pid> VM.native_memory summary

Object layout

Every object has a header — a mark word (identity hash, GC age, lock state) plus a class pointer — 12 bytes with compressed oops, padded to an 8-byte boundary. So the smallest object is 16 bytes, and an Integer spends 16 bytes to hold 4 bytes of data.

Compressed oops store 32-bit scaled offsets instead of 64-bit pointers, and they work up to about a 32 GB heap. That produces a genuinely counter-intuitive fact: a 31 GB heap can hold more objects than a 33 GB one, because crossing the threshold loses compression and inflates every reference by roughly 20%.

Cost
long[1_000_000]        ~  8 MB
Long[1_000_000]        ~ 24 MB   (8MB of references + 16MB of objects)
Interview angle

Escape analysis is the JIT determining whether an object can be seen outside the method that created it. If it cannot, three optimisations become legal: scalar replacement (the object is never allocated — its fields become registers), stack allocation, and lock elision. This is why "avoid allocation" is often wrong advice for short-lived locals — the JIT frequently removes them entirely.

Chapter 46

Garbage collection

GC rests on the generational hypothesis: most objects die young. So the heap is split into a young generation (Eden plus two survivor spaces) and an old generation. New objects go in Eden; a minor GC collects the young gen, copying the few survivors and promoting long-lived ones to old.

Because most objects die, a minor GC only has to trace and copy the small live set — collection cost is proportional to survivors, not to garbage. That is why allocating many short-lived objects is genuinely cheap in Java, and why object pooling is usually counterproductive: pooled objects survive, get promoted to old gen, and are traced on every collection.

The collectors

  • Serial — one thread, stop-the-world. Correct for tiny heaps and single-CPU containers.
  • Parallel — multi-threaded stop-the-world, maximum throughput, long pauses. Right for batch jobs.
  • CMS — the historic concurrent collector, removed in JDK 14. Fragmentation was its undoing.
  • G1 — the default since Java 9. The heap is divided into equal-sized regions, marked concurrently, and the regions with the most garbage are collected first (hence Garbage-First), choosing how many to fit a MaxGCPauseMillis target. That target is a goal, not a guarantee.
  • ZGC / Shenandoah — concurrent compaction using load and store barriers, giving sub-millisecond pauses largely independent of heap size, at a few percent of throughput.
Flags
-XX:+UseG1GC -XX:MaxGCPauseMillis=200      # balanced default
-XX:+UseZGC -XX:+ZGenerational             # strict tail latency, large heaps
-XX:+UseParallelGC                          # batch throughput

# always log it
-Xlog:gc*:file=gc.log:time,uptime,level,tags:filecount=5,filesize=20M

Reading a GC log

Look at four things: pause durations and their distribution; collection frequency; how much the heap drops at each collection — if the post-GC floor keeps rising you have a leak, not a tuning problem; and promotion and allocation rates.

Map symptoms to causes: frequent minor GCs with a low promotion rate is usually healthy. Frequent full GCs or a monotonically rising live set is a leak. "To-space exhausted" or promotion failures mean the young generation is mis-sized for your object lifetimes.

Interview angle

Before tuning anything, prove causation: correlate GC pause timestamps against your p99 latency timeline. If they do not line up, GC is not your problem — a very common false lead where the real cause is lock contention or a slow downstream. And the single flag that matters most is -Xmx: almost every GC problem is really a sizing problem or a leak.

Chapter 47

JIT compilation and warmup

The JVM starts by interpreting bytecode while collecting a profile — which methods are hot, which branches are taken, which receiver types appear at each call site. Tiered compilation then escalates: C1 compiles quickly with instrumentation still in place, and once a method is hot enough C2 compiles it aggressively using the profile C1 gathered.

Inlining is the enabling optimisation

Inlining pastes a callee's body into the caller, which then unlocks constant folding, escape analysis and lock elision. Methods above a bytecode-size threshold are not inlined, which is a genuine argument for keeping hot methods small. Virtual calls are devirtualized when the profile shows one or two receiver types; a megamorphic call site with three or more stays an indirect jump and blocks all downstream optimisation.

Deoptimization

These optimisations are speculative, guarded by cheap runtime checks. If a new class breaks a monomorphic assumption, or an "uncommon" branch is finally taken, the JVM discards the compiled code, falls back to the interpreter, and recompiles with the corrected profile. That is why performance can visibly change minutes into a run.

Flags
-XX:+PrintCompilation                                # what gets compiled, when
-XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining     # inlining decisions

Why warmup is an operational concern

A freshly started JVM is genuinely slower — interpreted, unprofiled, cold code cache. The consequences are practical: ramp traffic gradually to new instances (slow start on the load balancer) or pre-warm them, because sending full production load to a cold JVM produces a latency spike that can cascade into upstream timeouts. During a rolling deploy, every replacement instance is a small brownout unless you handle it.

Interview angle

The same fact is why a naive microbenchmark lies: without warmup you measured the interpreter. JMH exists to defeat exactly this — warmup iterations, a fresh JVM fork per trial so one benchmark's profile does not pollute another's, and Blackhole plus @State to prevent dead-code elimination and constant folding.

Chapter 48

OutOfMemoryError and memory leaks

OutOfMemoryError is not one condition — the message tells you which resource ran out, and each has a different fix. Reading the message is the first diagnostic step.

OOM variants
Java heap space              genuine heap exhaustion: leak, undersized, or one huge alloc
GC overhead limit exceeded   >98% of time in GC recovering <2% - a leak in its terminal phase
Metaspace                    class metadata - almost always a CLASSLOADER leak
unable to create new thread   OS/memory thread limit - usually an unbounded pool
Direct buffer memory          leaked NIO ByteBuffers
Requested array size exceeds  an array near Integer.MAX_VALUE

The classic leaks

In a garbage-collected language there are no leaks, only unintended reachability — objects you forgot you were still referencing.

  • Static collections that only ever grow — a cache with no eviction, a registry nobody unregisters from.
  • Listeners and callbacks never removed, which also pin whatever they close over.
  • ThreadLocals in pooled threads without remove() — the value is held by the long-lived thread.
  • Classloader leaks on redeploy (Metaspace, not heap).
  • Inner class instances pinning their outer object through the synthetic this$0 reference.

The diagnosis workflow

Workflow
jcmd <pid> GC.heap_dump /tmp/dump1.hprof
# ... run under load ...
jcmd <pid> GC.heap_dump /tmp/dump2.hprof

Eclipse MAT:
  1. Histogram -> COMPARE the two dumps -> which class is GROWING
  2. Dominator Tree -> sort by RETAINED size (not shallow)
  3. right-click -> Path to GC Roots -> exclude weak/soft references
  4. the chain terminates at a static field, a live thread, or a listener list

Two dumps, not one: a single snapshot tells you what is big, two tell you what is growing — and growth is what a leak is. Retained size is what would be freed if that object went away, which is what you actually care about; shallow size is just the object itself.

Interview angle

Always run production with -XX:+HeapDumpOnOutOfMemoryError and a writable path. An OOM without a heap dump is a lost investigation — you cannot reproduce it later, and the next occurrence is another outage. Pair it with -XX:+ExitOnOutOfMemoryError, because after an OOM the JVM is in an undefined state and a clean restart is more predictable than limping on.

Chapter 49

Profiling and production debugging

Learn the tools as a sequence, because that is how the question is asked: "a service is at 100% CPU with 8-second p99 — what do you do?"

Sequence
1. WHICH THREADS?
   top -H -p $PID                  # per-thread CPU; note the TID
   printf '%x\n' 12345             # TID -> hex nid
   jcmd $PID Thread.print | grep -A 30 'nid=0x3039'
   # take THREE dumps ~5s apart: same frame = stuck (lock/loop); different = working

2. RULE OUT GC
   correlate gc.log pause timestamps against the p99 timeline
   a GC death spiral presents exactly as 100% CPU with terrible latency

3. LOCK CONTENTION
   the thread dump shows BLOCKED threads and the monitor OWNER
   many threads blocked on one monitor = a serialization bottleneck

4. POOL EXHAUSTION  <- the trap
   threads parked in HikariPool.getConnection: CPU is LOW, DB looks idle, p99 explodes
   check hikaricp_connections_pending

5. PROFILE
   jcmd $PID JFR.start duration=60s filename=/tmp/rec.jfr settings=profile
   ./profiler.sh -d 30 -f flame.html $PID     # async-profiler flame graph

The discriminator

  • High CPU, threads in application code → a hot code path or an infinite loop.
  • High CPU, GC threads dominating → a memory problem, not a code problem.
  • Low CPU, high latency → blocking: a lock, a pool, or a slow downstream.

Why async-profiler

Many profilers can only sample at safepoints, so they systematically attribute time to safepoint-reachable code and miss tight loops that never reach one. That is safepoint bias. async-profiler uses OS-level perf events plus AsyncGetCallTrace, so its samples are unbiased — and the widest frame in the flame graph is your answer.

JFR (Java Flight Recorder) is built into the JDK, has very low overhead, and is safe to run continuously in production — so the data already exists when an incident starts, which is far better than trying to attach a profiler to a system that is on fire.

Interview angle

jcmd is the modern front door for all of it — Thread.print, GC.heap_dump, GC.heap_info, JFR.start, VM.native_memory. Knowing one command with subcommands is easier than remembering five separate tools, and it is what you will actually reach for.

VII. The Ecosystem
Chapter 50

Spring core and dependency injection

Inversion of Control means the framework creates and wires your objects instead of each class constructing its own dependencies. Dependency injection is how they arrive. The benefit is testability and swappability: your service takes a PaymentGateway interface and neither knows nor cares which implementation the container supplies.

Constructor injection is the correct default

It makes dependencies explicit and mandatory, allows final fields (so the object is immutable and safely publishable), fails fast at startup if something is missing, and lets you instantiate the class in a unit test with plain new — no Spring required. Since Spring 4.3, a single constructor needs no @Autowired annotation at all.

Java
@Service
class PaymentService {
    private final PaymentGateway gateway;      // final: set once, thread-safe
    private final LedgerRepository ledger;

    PaymentService(PaymentGateway gateway, LedgerRepository ledger) {   // no @Autowired
        this.gateway = gateway;
        this.ledger = ledger;
    }
}

// the unit test needs no Spring at all
var svc = new PaymentService(new FakeGateway(), new InMemoryLedger());

Field injection is the one to argue against: fields cannot be final, the class cannot be constructed without reflection so unit tests need the container, and it hides how many dependencies a class has — which conveniently disguises a god class. A constructor with eight parameters is visibly painful, and that pressure is a feature.

Lifecycle, scopes and the proxy point

The container instantiates the bean, injects dependencies, runs BeanPostProcessor.postProcessBeforeInitialization, calls @PostConstruct, then postProcessAfterInitialization — which is where AOP proxies are created. Knowing that one fact explains every @Transactional and @Cacheable surprise in the next chapter.

Scopes: singleton (one per container, so it must be stateless or thread-safe), prototype (a new instance per injection — and Spring does not manage its destruction), plus the web scopes. The classic bug is injecting a prototype or request-scoped bean into a singleton: injection happens once, so the singleton keeps the first instance forever. Fix with a scoped proxy or by injecting an ObjectProvider.

Interview angle

Circular dependencies are resolved for setter/field injection via a three-level cache of singletons, but cannot be for constructor injection — neither object can be constructed without the other. Since Boot 2.6 that fails at startup by default, and that is correct: a cycle almost always means a shared responsibility belongs in a third bean.

Chapter 51

@Transactional — everything follows from the proxy

Everything surprising about @Transactional follows from one fact: it is implemented by an AOP proxy. Spring wraps your bean; the proxy begins a transaction before the method and commits or rolls back after. Lead with that and the rest is derivation.

Self-invocation does nothing

If method a() calls this.b(), the call goes straight to the target object and never through the proxy — so @Transactional on b() is silently ignored. No error, no warning. The same reason it does nothing on private, final or static methods, and why a final class cannot be proxied at all (a real Kotlin gotcha, where classes are final by default).

Java
@Service
class OrderService {
    @Transactional
    public void place(Order o) {
        save(o);
        audit(o);            // self-invocation: @Transactional on audit() is IGNORED
        gateway.charge(o);   // NEVER: holds a DB connection across a remote call
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void audit(Order o) { }
}

Checked exceptions commit

By default Spring rolls back on RuntimeException and Error only. A checked exception commits unless you write rollbackFor = Exception.class. That default surprises almost everyone and is worth stating explicitly in an interview.

Propagation

  • REQUIRED (default) — joins an existing transaction, so an inner failure marks the whole thing rollback-only, producing the confusing "Transaction silently rolled back" error.
  • REQUIRES_NEW — suspends the current transaction and opens a second one on a different connection. It can deadlock against the first if both touch the same rows, and it consumes two pool connections for one request.
  • NESTED — uses savepoints.
  • MANDATORY / SUPPORTS — for enforcing caller contracts.

readOnly = true lets Hibernate skip dirty checking and lets some setups route to a read replica — a real optimisation on read-heavy endpoints that also documents intent.

Interview angle

The operational rule to close on: never make a remote call inside a transaction. You hold a database connection and its locks for the duration of someone else's outage, which converts a slow dependency into connection-pool exhaustion. To make something survive a rollback, use @TransactionalEventListener(phase = AFTER_COMMIT) or a separate bean with REQUIRES_NEW.

Chapter 52

JPA and Hibernate

The persistence context is the EntityManager for one transaction — a first-level cache and a unit of work. Entities are transient (new), managed (tracked), detached (context closed) or removed. Within one context, loading the same row twice returns the same object instance, which is why == works for entities inside a transaction.

Dirty checking

While an entity is managed, changing a field is enough — Hibernate compares against the snapshot taken at load and issues an UPDATE at flush. You never call save(). Powerful, and also a trap: an accidental setter inside a transaction writes to the database.

Java
@Transactional
void rename(Long id, String name) {
    Order o = repo.findById(id).orElseThrow();
    o.setName(name);              // dirty checking issues the UPDATE - no save() needed
}

Flush is not commit. Hibernate flushes before a query that might be affected by pending changes, and at commit. That explains why your INSERT appears at a surprising point — and why a batch loop needs flush() then clear(), or the context accumulates every entity and dirty-checks all of them on each flush, making the job quadratic.

N+1 — the most common ORM bug

One query for parents, then one per parent for a lazy association. 200 orders becomes 201 round trips, each paying network latency. It passes tests with ten rows and dies in production.

Java
// diagnose by COUNTING queries, never by inspection
spring.jpa.properties.hibernate.generate_statistics=true

// fix per query - not by changing the mapping
@Query("select distinct o from Order o join fetch o.lines where o.status = :s")
List<Order> findWithLines(@Param("s") Status s);

@EntityGraph(attributePaths = "lines")
List<Order> findByStatus(Status s);

@BatchSize(size = 50) @OneToMany(mappedBy = "order") List<Line> lines;

Do not fix it by setting the mapping to EAGER — that is a global decision for a local problem, and it makes every query everywhere load the association.

LazyInitializationException and OSIV

Touching a lazy proxy after the context closed — typically during JSON serialization in the controller. Open Session In View (on by default in Spring Boot) hides it by holding the session for the whole request, and it is a bad fix: it holds a database connection through view rendering and any remote call, so under load the pool is exhausted by requests doing no database work, and it silently reintroduces N+1 during serialization where your service tests will never see it.

Interview angle

Set spring.jpa.open-in-view=false, decide the fetch plan explicitly inside the transaction, and map to a DTO. Then any remaining LazyInitializationException is telling you about a genuinely missing fetch plan — which is exactly the feedback you want.

Chapter 53

Testing

Structure it as a pyramid with a specific shape for Spring. Most tests should be plain unit tests — new the class, pass fakes, assert. No Spring context, milliseconds each. That speed is what keeps the suite usable, and constructor injection is what makes it possible.

Use slices in the middle: @WebMvcTest loads only the web layer with MockMvc; @DataJpaTest only JPA with a transactional rollback per test. Reserve full @SpringBootTest for a handful of end-to-end paths — it starts the whole context, and its context caching is easily defeated by inconsistent configuration, so a suite of slightly-different variants starts a new context for each and takes minutes.

Mocks, stubs and fakes

  • A stub returns canned answers.
  • A mock also asserts on interactions.
  • A fake is a working lightweight implementation — an in-memory repository.

Prefer fakes. Mocks assert on how the code works, so they break on every refactoring even when behaviour is unchanged; fakes assert on outcomes and survive restructuring. And the rule: do not mock what you do not own — mocking a third-party client encodes your assumption about it, so if the assumption is wrong the test still passes. Wrap it in your own interface, fake that, and cover the real thing with one integration test.

Async and Testcontainers

Never Thread.sleep. Use Awaitility to poll a condition with a timeout — faster and non-flaky. And Testcontainers changes the calculus by making the real dependency cheap: a real Postgres, Kafka or Redis in Docker. Testing against H2 when production runs Postgres hides dialect differences, missing JSONB and different locking semantics — bugs that pass locally and fail in production.

Java
@Testcontainers @SpringBootTest
class OrderIT {
    @Container static PostgreSQLContainer<?> db =
            new PostgreSQLContainer<>("postgres:16");   // static = reused, fast

    @DynamicPropertySource
    static void props(DynamicPropertyRegistry r) { r.add("spring.datasource.url", db::getJdbcUrl); }

    @Test void publishesEvent() {
        service.place(order);
        await().atMost(5, SECONDS)                       // Awaitility, not sleep
               .untilAsserted(() -> assertThat(consumed()).hasSize(1));
    }
}
Interview angle

Watch @MockBean's hidden cost: each distinct set of mocked beans produces a different application context, and Spring caches contexts by configuration — ten variations means ten context startups. Prefer constructor-injected fakes in unit tests and keep the mocked-bean variations few.

Chapter 54

Build tools and dependencies

Both Maven and Gradle resolve transitive dependencies, but with different conflict rules — and that difference causes real, confusing bugs.

Resolution
Maven   NEAREST-WINS   the version at the shallowest depth in the tree
Gradle  HIGHEST-WINS    the newest version anyone requested

# the same dependency graph can produce DIFFERENT runtime versions in each tool

Learn to read the tree, because NoSuchMethodError or NoClassDefFoundError at runtime is almost always "I compiled against one version and am running against another" — a resolution problem, not a code problem.

Shell
mvn dependency:tree -Dincludes=com.fasterxml.jackson.core:jackson-databind
mvn dependency:analyze          # used-but-undeclared / declared-but-unused
gradle dependencyInsight --dependency jackson-databind

Pin versions centrally with a BOM

A bill of materials fixes versions in one place. The Spring Boot BOM exists precisely so the dozens of libraries it pulls in remain mutually compatible — you should almost never specify a version for anything it manages.

XML
<dependencyManagement><dependencies><dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-dependencies</artifactId>
  <version>3.3.0</version><type>pom</type><scope>import</scope>
</dependency></dependencies></dependencyManagement>

Shading

Relocating a dependency's packages into your own namespace at build time solves the case where you and a dependency need genuinely incompatible versions of the same library. It is a library author's tool — it makes your artifact self-contained at the cost of a larger jar, duplicated classes across the ecosystem, and broken debugging. Using it in an application almost always means the dependency graph needs cleaning instead.

Interview angle

Keep a vulnerability scanner in CI. Most real-world Java breaches arrive through a known CVE in a transitive dependency — Log4Shell being the obvious example — not through code anyone wrote. Dependency scanning plus a fast patch process outranks most code-level hardening.

Chapter 55

Security essentials

Injection

In Java this is almost always SQL built by string concatenation. The fix is parameter binding — PreparedStatement, JPQL parameters, Spring Data. The case that catches people is that you cannot parameterize SQL structure: a dynamic ORDER BY or table name must be validated against an allowlist of known column names.

Java
private static final Set<String> SORTABLE = Set.of("created_at","amount","status");
String sort = SORTABLE.contains(req.sort()) ? req.sort() : "created_at";   // allowlist
jdbc.query("select * from orders where account_id = ? order by " + sort,
           mapper, accountId);                                    // value is BOUND

Allowlist rather than escaping or blocklisting: escaping must anticipate every encoding, and an attacker only needs one you missed.

Mass assignment

Binding @RequestBody directly to a JPA entity lets a caller set any field the entity exposes — role, balance, isVerified. Always bind to a request DTO containing only the fields a client may legitimately set, and map explicitly. A one-line vulnerability, trivially exploitable, extremely common.

SSRF

Any feature that fetches a user-supplied URL — webhook registration, image import, link preview — lets an attacker reach your internal network and cloud metadata endpoints to steal credentials. Allowlist hosts, and block private and link-local ranges after DNS resolution (to defeat rebinding), not by inspecting the hostname.

Deserialization and secrets

Never deserialize untrusted Java-serialized data: it constructs objects without running constructors, bypassing every invariant, and the byte stream chooses which classes get instantiated — the root of a long line of RCE CVEs. With Jackson, never enable default polymorphic typing, which reintroduces the same hole.

Secrets come from environment variables or a vault — never committed YAML, never logs, never toString(). Rotate them, and scan git history: a secret committed once is compromised even after removal.

Interview angle

If you take one thing from this chapter: validate at the boundary, bind parameters, and allowlist anything structural. Those three cover the majority of application-level Java vulnerabilities, and the remaining majority of incidents come from unpatched dependencies rather than from code.

Chapter 56

How to answer a Java interview question

Knowing the material is necessary and not sufficient. How you deliver it is separately scored, and it is the easier thing to improve.

Lead with the mechanism, not the symptom

Almost every Java answer is stronger when you start from the underlying mechanism, because one mechanism explains many symptoms. "@Transactional is implemented by a proxy" immediately explains self-invocation, private methods and final classes. "hooks are a positional linked list on the fiber" explains all the rules of hooks. Reciting three symptoms sounds memorised; deriving them from one mechanism sounds understood.

Name the failure the feature prevents

Java's APIs mostly exist to stop specific bugs. "Keys let React match children across renders" is a textbook definition; "without stable keys, deleting a row leaves the typed text on the wrong row" is experience. The same applies throughout: describe what breaks without hashCode, without the cleanup, without the bounded queue.

Volunteer the cost

Anyone can name a pattern. Naming what it costs is what demonstrates you have paid it. "Use a cache" versus "cache when reads dominate and staleness is tolerable — and accept that for up to one TTL a user may see a stale value, which was acceptable here because…" The second answer is the Software Engineer one, and the difference is one sentence.

Say when you do not know

"I have not used that in production, but based on how X works I would expect…" is a strong answer. Inventing detail is the only guaranteed failure, because the next question always finds it. Nobody knows everything, and interviewers are calibrating your self-assessment as much as your knowledge.

The four to be perfect on

If you can explain each of these cleanly in under two minutes without notes, the Java track of a Software Engineer loop is in good shape:

  • The hashCode contract and the exact HashMap failure when you break it.
  • The Java Memory Model — happens-before, and why volatile is not atomicity.
  • Thread pool sizing and the unbounded-queue trap.
  • @Transactional proxying and self-invocation.
Interview angle

An interview is a conversation between engineers about a problem, not an examination. Ask clarifying questions, think out loud, state your assumptions, and react to what the interviewer says. Candidates who engage consistently outperform candidates who perform — and after working through this handbook, you have the material to engage with.

56 chapters · Java Ground Up

Back to the ledger →

Made By Jatin Bhargava · 2026