Skip to main content
Backend & Systems

Java Interview Questions

All Levels (Junior to Staff)16 Questions

JVM architecture masterclass: garbage collection algorithms (G1, ZGC), Java Memory Model (JMM), thread safety, synchronized vs Lock, and Spring Boot DI.

25 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice Java Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

Is Java pass-by-value or pass-by-reference when passing objects to a method?

Senior Engineering Answer

Java is strictly pass-by-value in all cases. For primitives, the value itself is copied onto the callee's stack frame. For objects, the value of the reference (the memory handle pointing to the object on the heap) is copied by value. Consequently, mutating a field through that copied reference affects the original heap object, but reassigning the parameter variable inside the method only updates the local copy and never changes the caller's reference.

Production Code Example
void reassignVsMutate(StringBuilder sb) {
    sb.append(" world");          // Mutates the shared heap object
    sb = new StringBuilder("new"); // Rebinds local copy only
}

StringBuilder s = new StringBuilder("hello");
reassignVsMutate(s);
System.out.println(s); // Prints "hello world"
Common Interview Trap / Anti-Pattern:

Saying 'primitives are passed by value and objects are passed by reference.' If Java had pass-by-reference, a swap(a, b) method could swap two caller object references, which is impossible in Java.

Question #2FundamentalJunior

What is the contract between equals() and hashCode(), and what breaks if you override only one?

Senior Engineering Answer

The Object contract states that if a.equals(b) is true, then a.hashCode() == b.hashCode() must also be true (the converse is not required because hash collisions are allowed). Hash-based collections like HashMap and HashSet use hashCode() to select a bucket and only call equals() on entries within that bucket. If you override equals() without hashCode(), two logically equal objects land in different buckets, causing HashMap.get() to return null and HashSet to store duplicates.

Production Code Example
public final class UserKey {
    private final long tenantId;
    private final String email;

    public UserKey(long tenantId, String email) {
        this.tenantId = tenantId;
        this.email = email;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof UserKey other)) return false;
        return tenantId == other.tenantId && Objects.equals(email, other.email);
    }

    @Override
    public int hashCode() {
        return Objects.hash(tenantId, email);
    }
}
Common Interview Trap / Anti-Pattern:

Using mutable fields in hashCode() for keys stored in a HashMap: mutating the field after insertion changes the hash bucket, making the entry unreachable even with the exact same object reference.

Question #3FundamentalJunior

Why is String immutable in Java, and how does the String Pool interact with new String() vs literals?

Senior Engineering Answer

String immutability enables safe sharing in the String Pool (intern table), guarantees hashCode caching for fast HashMap lookups, prevents security issues when passing file paths or JDBC URLs, and ensures thread safety without synchronization. String literals are interned automatically into the String Pool in heap memory. Calling new String("abc") allocates a distinct String instance on the regular heap even if "abc" already exists in the pool, unless .intern() is explicitly invoked.

Production Code Example
String a = "hello";
String b = "hello";
String c = new String("hello");

System.out.println(a == b);          // true (same pooled reference)
System.out.println(a == c);          // false (heap object vs pool)
System.out.println(a == c.intern()); // true
Common Interview Trap / Anti-Pattern:

In Java 9+, Compact Strings store Latin-1 strings in a byte[] (1 byte per char) instead of char[] (2 bytes per char) and switch to UTF-16 only when non-Latin-1 characters appear—mentioning char[] alone is outdated.

Question #4FundamentalJunior

What are the differences between checked exceptions, unchecked exceptions, and Errors in Java?

Senior Engineering Answer

Throwable has two branches: Error and Exception. Errors (such as OutOfMemoryError or StackOverflowError) represent unrecoverable JVM/system conditions that applications should generally not catch. Checked exceptions (subclasses of Exception excluding RuntimeException, e.g., IOException) are enforced at compile time and must be caught or declared in throws, representing recoverable external conditions. Unchecked exceptions (subclasses of RuntimeException, e.g., NullPointerException, IllegalArgumentException) indicate programming bugs or unrecoverable domain violations and do not require throws declarations.

Production Code Example
try (BufferedReader reader = Files.newBufferedReader(path)) {
    return reader.readLine();
} catch (IOException e) { // Checked exception handled with try-with-resources
    throw new UncheckedIOException("Failed reading config", e);
}
Common Interview Trap / Anti-Pattern:

Swallowing checked exceptions in an empty catch block or catching broad Exception/Throwable, which can accidentally mask InterruptedException or OutOfMemoryError.

Question #5IntermediateMid-Level

How does HashMap handle hash collisions internally in Java 8 and later?

Senior Engineering Answer

Java 8+ HashMap stores entries in an array of Node buckets, initially chaining colliding keys in a singly linked list. When a single bucket's chain length reaches TREEIFY_THRESHOLD (8) and the total table capacity is at least MIN_TREEIFY_CAPACITY (64), the bucket converts into a balanced Red-Black tree (TreeNode), improving worst-case lookup from O(n) to O(log n). If the bucket shrinks below UNTREEIFY_THRESHOLD (6) during resizing or removals, it converts back to a linked list.

Production Code Example
// HashMap spreads high bits into low bits to reduce collisions
static int spreadHash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
Common Interview Trap / Anti-Pattern:

Assuming HashMap resizes immediately on any collision: resizing occurs when size exceeds capacity * loadFactor (default 16 * 0.75 = 12), and treeification only happens if table length >= 64.

Question #6IntermediateMid-Level

How does ConcurrentHashMap achieve high concurrency without locking the entire map?

Senior Engineering Answer

Since Java 8, ConcurrentHashMap abandoned Java 7 segment locking in favor of bucket-level synchronization. Reads (get) are completely lock-free using volatile reads of the table array and Node value/next pointers. Writes (put/compute) use Compare-And-Swap (CAS) to insert into an empty bucket without locking, and acquire a synchronized monitor only on the head Node of the target bucket when a collision occurs. Null keys and null values are disallowed to avoid ambiguity between absent keys and mapped nulls under concurrency.

Production Code Example
ConcurrentHashMap<String, LongAdder> counters = new ConcurrentHashMap<>();
// Atomic per-key accumulation without external locking
counters.computeIfAbsent("http_500", k -> new LongAdder()).increment();
Common Interview Trap / Anti-Pattern:

Performing compound check-then-act logic like if (!map.containsKey(k)) map.put(k, v) on a ConcurrentHashMap—that sequence is not atomic; use putIfAbsent or computeIfAbsent instead.

Question #7IntermediateMid-Level

What are Java Records and Sealed Classes, and how do they improve domain modeling?

Senior Engineering Answer

Records (Java 16+) are transparent, shallowly immutable data carriers whose state is fully defined by their header components; the compiler generates canonical constructors, accessors, equals, hashCode, and toString automatically. Sealed classes and interfaces (Java 17+) restrict which types may extend or implement them via a permits clause. Combined with Java 21 pattern matching for switch, they enable exhaustive algebraic data types checked at compile time without default branches.

Production Code Example
public sealed interface PaymentResult permits Approved, Declined {}
public record Approved(String txId, long amountCents) implements PaymentResult {}
public record Declined(String reason) implements PaymentResult {}

String summarize(PaymentResult res) {
    return switch (res) {
        case Approved(var txId, var amt) -> "OK: " + txId + " (" + amt + ")";
        case Declined(var reason) -> "Failed: " + reason;
    };
}
Common Interview Trap / Anti-Pattern:

Assuming a Record is deeply immutable: if a record holds a mutable List or array component, callers can mutate it unless you make a defensive copy (List.copyOf) inside a compact constructor.

Question #8IntermediateMid-Level

What are the pitfalls of Java parallelStream() in backend services?

Senior Engineering Answer

By default, parallelStream() executes tasks on the JVM-wide ForkJoinPool.commonPool(), whose size defaults to CPU cores minus one. If any parallel stream performs blocking I/O (HTTP calls, JDBC queries), it starves the shared common pool across the entire application, degrading unrelated CompletableFuture or stream workloads. Additionally, parallel streams add splitting, thread-handoff, and merging overhead, making them slower than sequential loops for small collections or LinkedList sources that split poorly.

Production Code Example
// Isolated custom ForkJoinPool instead of polluting commonPool
ForkJoinPool customPool = new ForkJoinPool(4);
try {
    List<Result> results = customPool.submit(() ->
        items.parallelStream().map(this::cpuIntensiveTransform).toList()
    ).get();
} finally {
    customPool.shutdown();
}
Common Interview Trap / Anti-Pattern:

Using parallelStream() inside synchronized blocks or mutating shared non-thread-safe collections (like ArrayList) inside forEach(), which causes race conditions or corrupted state.

Question #9AdvancedSenior

How do Java 21 Virtual Threads (Project Loom) work internally, and what causes carrier thread pinning?

Senior Engineering Answer

Virtual threads are lightweight user-mode threads scheduled by the JVM onto a small ForkJoinPool of carrier platform (OS) threads. When a virtual thread hits a blocking JDK I/O operation or LockSupport.park(), the JVM unmounts its stack frames (continuation) into the heap and frees the carrier thread to run another virtual thread. However, on Java 21-23, entering a synchronized block/method or executing a native JNI frame pins the virtual thread to its OS carrier thread if it blocks inside, preventing unmounting and risking thread starvation under load (Java 24 JEP 491 resolves synchronized pinning).

Production Code Example
// Prefer ReentrantLock over synchronized around I/O in Java 21 Virtual Threads
private final ReentrantLock lock = new ReentrantLock();

public String fetchWithLock() throws IOException {
    lock.lock();
    try {
        return httpClient.get();
    } finally {
        lock.unlock();
    }
}
Common Interview Trap / Anti-Pattern:

Pooling virtual threads in a fixed-size ExecutorService: virtual threads are cheap (~hundreds of bytes) and meant to be created per task via Executors.newVirtualThreadPerTaskExecutor(), never pooled, and concurrency limits should use a Semaphore.

Question #10AdvancedSenior

How does the Java Memory Model (JMM) establish happens-before relationships with volatile and synchronized?

Senior Engineering Answer

The JMM defines when writes by one thread become visible to another despite CPU store buffers, L1/L2 caches, and JIT/CPU instruction reordering. A write to a volatile variable happens-before every subsequent read of that same volatile variable, emitting memory barriers that prevent reordering across the access and ensure cache coherence. Similarly, unlocking a monitor happens-before every subsequent lock of the same monitor, guaranteeing both mutual exclusion and visibility of all prior writes.

Production Code Example
public final class SafeSingleton {
    private static volatile SafeSingleton instance;

    public static SafeSingleton getInstance() {
        SafeSingleton local = instance;
        if (local == null) {
            synchronized (SafeSingleton.class) {
                local = instance;
                if (local == null) {
                    local = instance = new SafeSingleton();
                }
            }
        }
        return local;
    }
}
Common Interview Trap / Anti-Pattern:

Forgetting volatile in double-checked locking: without volatile, another thread can observe a non-null reference to a partially constructed object because allocation and constructor writes can be reordered.

Question #11AdvancedSenior

How does JVM ClassLoader delegation work, and why do servlet containers or plugin systems invert it?

Senior Engineering Answer

Standard JVM ClassLoaders use a parent-first delegation model: Bootstrap -> Platform -> Application (System) ClassLoader. When asked to load a class, a ClassLoader delegates to its parent first and only loads the class itself if the parent throws ClassNotFoundException, ensuring core java.* classes cannot be spoofed. Servlet containers (like Tomcat) or OSGi modules invert this to child-first delegation for non-JDK packages so multiple deployed applications can load conflicting versions of the same library without colliding.

Production Code Example
// Class uniqueness in the JVM is (fullyQualifiedName, definingClassLoader)
Class<?> c1 = loaderA.loadClass("com.example.Plugin");
Class<?> c2 = loaderB.loadClass("com.example.Plugin");
// c1 != c2 and casting an instance of c1 to c2 throws ClassCastException
Common Interview Trap / Anti-Pattern:

ClassLoader memory leaks in dynamic reload scenarios: if a thread pool, ThreadLocal, or JDBC DriverManager retains a reference to a class loaded by a child ClassLoader, the entire ClassLoader and its Metaspace metadata cannot be garbage collected.

Question #12AdvancedSenior

How do you diagnose and prevent off-heap memory leaks and DirectByteBuffer OOMs in JVM services?

Senior Engineering Answer

Off-heap memory includes Metaspace, thread stacks, JNI/native allocations, and DirectByteBuffers allocated via ByteBuffer.allocateDirect() (heavily used by Netty, Kafka, and gRPC). Heap tools like standard GC logs do not capture native allocations directly. Diagnosing requires enabling -XX:NativeMemoryTracking=summary (or detail) and inspecting with jcmd <pid> VM.native_memory, capping direct memory with -XX:MaxDirectMemorySize, and ensuring pooled Netty ByteBufs are explicitly released via reference counting.

Production Code Example
// Netty off-heap buffer must be released to prevent native leak
ByteBuf buf = alloc.directBuffer(4096);
try {
    buf.writeBytes(payload);
    channel.writeAndFlush(buf.retain());
} finally {
    buf.release();
}
Common Interview Trap / Anti-Pattern:

Relying solely on -Xmx to bound container memory: in Kubernetes, if heap is set to 80% of container memory, off-heap buffers, Metaspace, and thread stacks can push RSS past the cgroup limit and trigger a Linux OOM killer SIGKILL.

Question #13StaffPrincipal / Staff

Compare G1 GC and Generational ZGC internals: how does ZGC achieve sub-millisecond pauses on multi-terabyte heaps?

Senior Engineering Answer

G1 divides the heap into regions and performs evacuation (copying live objects out of garbage-dense regions) during Stop-The-World (STW) pauses, making pause times proportional to the size of the live set in the collection set. ZGC uses colored pointers (storing metadata bits in 64-bit object references) and load barriers (tiny JIT-emitted checks when reading an object reference from the heap). This enables ZGC to mark, relocate, and remap references concurrently while application threads run, keeping STW pauses strictly under 1ms (typically <250 microseconds) independent of heap size.

Production Code Example
// Recommended JDK 21+ flags for Generational ZGC
// java -XX:+UseZGC -XX:+ZGenerational -Xms16g -Xmx16g -jar service.jar
Common Interview Trap / Anti-Pattern:

Assuming ZGC always has higher throughput than G1: ZGC trades some CPU overhead (load barriers and concurrent worker threads) for ultra-low tail latency; if allocation rate outpaces ZGC's concurrent reclamation, application threads experience allocation stalls.

Question #14StaffPrincipal / Staff

What are JVM Safepoints and Time-To-Safepoint (TTSP) stalls, and how can they cause unexpected latency spikes?

Senior Engineering Answer

A JVM safepoint is a global point where all application threads pause so the JVM can safely inspect stacks, perform GC root scanning, deoptimize JIT code, or dump threads. All threads must reach a safepoint check before the operation begins. If one thread is executing a tight counted loop (e.g., an int-indexed loop without safepoint polls before loop strip mining) or a long JNI copy, every other thread sits idle waiting for it—creating a Time-To-Safepoint (TTSP) tail-latency spike even when the actual GC pause is short.

Production Code Example
// Inspect safepoint pauses and TTSP in production
// -Xlog:safepoint=info:file=safepoint.log:time,uptime,level,tags
Common Interview Trap / Anti-Pattern:

Blaming the garbage collector for a 500ms pause when GC logs show the actual GC work took 8ms and 492ms was spent waiting for one thread to reach a safepoint (or writing GC logs synchronously to a stalled disk).

Question #15StaffPrincipal / Staff

Why are ScopedValues preferred over ThreadLocals when using Virtual Threads and Structured Concurrency?

Senior Engineering Answer

ThreadLocal stores a mutable map entry per thread that persists for the thread's entire lifetime unless remove() is manually called—catastrophic when millions of short-lived virtual threads are spawned or when InheritableThreadLocal copies the entire map to child threads. ScopedValue (preview/finalizing in modern JDKs) binds an immutable value strictly to the lexical scope of a dynamic call stack, supports zero-copy inheritance across StructuredTaskScope child virtual threads, and automatically unbinds when the scope exits.

Production Code Example
private static final ScopedValue<RequestContext> CTX = ScopedValue.newInstance();

ScopedValue.where(CTX, new RequestContext(traceId)).run(() -> {
    handleRequest(); // CTX.get() is visible down the call stack and child tasks
});
Common Interview Trap / Anti-Pattern:

Using ThreadLocal caches (like per-thread SimpleDateFormat or byte[] scratch buffers) with virtual threads: instead of 200 cached objects in a platform thread pool, 100,000 virtual threads will allocate 100,000 separate copies and exhaust heap.

Question #16StaffPrincipal / Staff

How do JIT tiered compilation, escape analysis, and devirtualization optimize Java throughput at runtime?

Senior Engineering Answer

HotSpot uses tiered compilation: bytecode starts interpreted, compiles with C1 (fast startup, profiling counters), and hot methods compile with C2 (aggressive optimization using runtime profile data). Escape analysis determines whether an object's reference never escapes a method or thread, enabling scalar replacement (eliminating heap allocation entirely and keeping fields in CPU registers) and lock elision. Class Hierarchy Analysis (CHA) allows C2 to speculatively devirtualize and inline interface/virtual calls when only one or two concrete implementations are observed at runtime, guarding with a fast check and deoptimizing if a new subclass is loaded later.

Production Code Example
// Scalar replacement eliminates Point allocation at runtime via Escape Analysis
int manhattanDistance(int x1, int y1, int x2, int y2) {
    record Point(int x, int y) {}
    Point p1 = new Point(x1, y1);
    Point p2 = new Point(x2, y2);
    return Math.abs(p1.x() - p2.x()) + Math.abs(p1.y() - p2.y());
}
Common Interview Trap / Anti-Pattern:

Writing microbenchmarks with naive System.nanoTime() loops: without JMH (Java Microbenchmark Harness) warmup and Blackhole consumption, JIT dead-code elimination and constant folding can optimize away the entire benchmarked computation.

Java Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This Java preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Backend & Systems.

JuniorFundamental

Is Java pass-by-value or pass-by-reference when passing objects to a method?

JuniorFundamental

What is the contract between equals() and hashCode(), and what breaks if you override only one?

JuniorFundamental

Why is String immutable in Java, and how does the String Pool interact with new String() vs literals?

JuniorFundamental

What are the differences between checked exceptions, unchecked exceptions, and Errors in Java?

Mid-LevelIntermediate

How does HashMap handle hash collisions internally in Java 8 and later?

Mid-LevelIntermediate

How does ConcurrentHashMap achieve high concurrency without locking the entire map?

Frequently Asked Technical Interview Questions (Java)

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

How do Java 21 Virtual Threads differ from platform OS threads under high concurrency?
Platform threads map 1:1 to OS kernel threads, reserving ~1MB of stack memory and limiting concurrency to a few thousand threads due to kernel scheduling overhead. Virtual Threads are lightweight user-mode threads managed by the JVM whose continuations park on the heap during blocking I/O, allowing millions of concurrent tasks over a small pool of OS carrier threads.
When should a team choose G1 GC versus Generational ZGC?
G1 GC is the default balanced collector optimized for overall throughput with target pause times around tens of milliseconds. Generational ZGC uses colored pointers and load barriers to perform relocation concurrently, keeping pause times consistently under 1ms for latency-sensitive services and multi-hundred-gigabyte heaps at a modest CPU overhead.
Why does breaking the equals() and hashCode() contract corrupt HashMaps?
HashMap determines the storage bucket from hashCode() before checking key equality with equals(). If two logically equal keys return different hash codes, HashMap places or searches for them in different buckets, causing missed lookups in HashMap and duplicate entries in HashSet.
How does the Java Memory Model guarantee cross-thread visibility with volatile and synchronized?
Because CPU cores buffer writes in local caches and compilers reorder instructions, one thread's writes may not be visible to another. Marking a field volatile establishes a happens-before edge between writes and subsequent reads, while synchronized flushes and invalidates cached memory across monitor unlock and lock boundaries.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks