Java 8 to Java 21: Top 40 Interview Questions for Senior Software Engineers & Tech Leads
The definitive 2026 guide covering the 40 essential modern Java interview questions across Java 8 through Java 21, concurrency, JVM internals, virtual threads, and production scenarios.
Vivek Adarsh
Founder & Systems Architect, Veltoryx Technologies · Published November 5, 2026
If you are interviewing for a Senior Java Developer, Staff Software Engineer, or Technical Lead role in 2026, the bar is dramatically higher than it was a few years ago.
Interviewers expect you to know far more than basic syntax. They expect an architectural understanding of how the platform evolved from Java 8's functional streams all the way to Java 21's Virtual Threads (Project Loom), Generational ZGC, Structured Concurrency, and real-world production incident response.
Here is your comprehensive, battle-tested playbook covering 40 top questions across 6 core domains.
Part 1: Java 8 — Core Features
1. What are Functional Interfaces and Lambda Expressions?
A Functional Interface is an interface that contains exactly one abstract method (SAM - Single Abstract Method). It can have any number of default or static methods. The @FunctionalInterface annotation is optional but recommended as it forces the compiler to verify SAM compliance.
A Lambda Expression is an anonymous function—a block of code with parameters and a body that can be passed around as data. Under the hood, lambdas do not compile into anonymous inner classes; instead, Java uses the invokedynamic JVM bytecode instruction with LambdaMetafactory to dynamically construct lightweight call sites at runtime with near-zero memory footprint.
@FunctionalInterface
public interface OrderValidator {
boolean validate(Order order); // Single abstract method
default OrderValidator and(OrderValidator other) {
return order -> this.validate(order) && other.validate(order);
}
}Learn the four standard functional categories (Function<T,R>, Predicate<T>, Consumer<T>, Supplier<T>) in our Java Functional Interfaces Masterclass.
2. How do map() and flatMap() differ?
map(Function<T, R>): One-to-one transformation. It takes a value of typeTand maps it to a value of typeR. If the function returns a stream or container,map()returns a stream of streams (Stream<List<String>>).flatMap(Function<T, Stream<R>>): One-to-many transformation with flattening. It transforms each element into an individual stream and flattens all resulting sub-streams into a single unifiedStream<R>.
List<List<String>> nested = List.of(List.of("A", "B"), List.of("C", "D"));
// map() produces Stream<List<String>>
List<List<String>> mapped = nested.stream().map(list -> list).toList();
// flatMap() flattens to Stream<String> -> ["A", "B", "C", "D"]
List<String> flat = nested.stream().flatMap(Collection::stream).toList();3. How does Stream API work internally?
A Java Stream is not a data structure; it does not store elements. Internally, a stream consists of three stages:
- Source Spliterator: Wraps the backing collection and defines how elements are traversed and partitioned.
- Pipeline of Operations: Intermediate operations are modeled as a doubly linked list of
ReferencePipelinestages. Each stage implements aSink<T>interface containingbegin(),accept(T value), andend(). - Terminal Operation: Initiates data consumption. It links the downstream sinks backward to the source and pulls data through a single, fused for-loop.
4. What is lazy evaluation in Streams?
Intermediate operations (filter(), map(), sorted()) do not execute when called. They merely append a Sink node to the pipeline.
Execution is triggered only when a terminal operation (collect(), findFirst(), count()) is invoked. Furthermore, streams process elements vertically (one element through all stages) rather than horizontally, allowing short-circuiting operations like findFirst() to terminate the entire pipeline after examining only the first matching item.
5. Future vs CompletableFuture?
Future<T>(Java 5): Represents an asynchronous result, but is fundamentally blocking. The only way to retrieve the result is by calling.get(), which blocks the caller thread. It has no native support for chaining, combining, or exception callbacks.CompletableFuture<T>(Java 8): A non-blocking, event-driven reactive promise. It allows declarative chaining (.thenApply(),.thenCompose()), fan-out combining (CompletableFuture.allOf()), and asynchronous error recovery (.exceptionally()).
CompletableFuture.supplyAsync(() -> userService.fetchUser(userId))
.thenApplyAsync(user -> taxService.computeTax(user))
.thenAccept(invoice -> notificationService.send(invoice))
.exceptionally(ex -> {
log.error("Failed to process invoice", ex);
return null;
});6. How does Optional help avoid null checks?
Optional<T> is a value-based monad designed as a method return type to clearly signal to API callers that a return value may be absent, eliminating unexpected NullPointerException errors.
7. Default vs static methods in interfaces?
- Default methods (
default void log()): Virtual instance methods with a default implementation. They enable backward compatibility in interfaces without breaking existing implementing classes. Implementing classes can override them. - Static methods (
static Utility create()): Belong directly to the interface class namespace. They cannot be overridden by implementing classes and serve as cohesive utility or factory methods.
Part 2: Java 9 to Java 11
8. What is the Java Platform Module System (JPMS)?
Introduced in Java 9 (Project Jigsaw), JPMS organizes packages into modules defined by a module-info.java file.
It introduces two fundamental architectural invariants:
- Strong Encapsulation: Packages are private by default unless explicitly exported via
exports com.mycorp.api;. Even Java reflection cannot access unexported internal packages unless explicitly allowed viaopens. - Reliable Configuration: Modules explicitly declare their dependencies (
requires transitive com.fasterxml.jackson.databind;), allowing the JVM to verify the dependency graph at startup rather than crashing at runtime withNoClassDefFoundError.
9. List.of() vs Arrays.asList()?
| Feature | Arrays.asList(arr) (Java 1.2) | List.of(e1, e2) (Java 9) |
|---|---|---|
| Mutability | Mutably backed by array (can set(), cannot add()) | Completely Immutable (set() throws UnsupportedOperationException) |
| Null Elements | Allows null | Rejects null (throws NullPointerException) |
| Array Linkage | Modifying original array mutates the list | Creates an independent, space-efficient compact instance |
10. What are private interface methods?
Introduced in Java 9, interfaces can declare private and private static methods. They prevent code duplication by allowing multiple default or static methods within the same interface to share common helper logic without exposing internal routines to implementing classes.
11. What is var in Java?
Introduced in Java 10 for local variables, var provides compile-time type inference.
// Clean and readable without redundant type repetition
var orderRepository = new OrderRepository();
var userMap = new ConcurrentHashMap<String, List<Order>>();12. What new String methods were introduced in Java 11?
Java 11 supercharged java.lang.String with essential functional utilities:
isBlank(): Checks if string is empty or contains only whitespace (faster than trim).lines(): Returns aStream<String>split by line terminators (\n,\r\n).strip(),stripLeading(),stripTrailing(): Unicode-aware whitespace removal (superior to legacy ASCIItrim()).repeat(int count): Multiplies string content without manual loop allocation.
Deep dive into the modular system and Java 11 runtime changes in our Java 9 to 11 Features & JPMS Guide.
Part 3: Java 12 to Java 17 LTS
13. What are Switch Expressions?
Introduced as standard in Java 14, switch expressions allow switch blocks to return values directly using the -> arrow syntax with exhaustive compile-time checks and no fall-through (eliminating the need for error-prone break; statements):
String priority = switch (status) {
case CRITICAL, BLOCKER -> "P0";
case HIGH -> "P1";
case MEDIUM, LOW -> "P2";
default -> "P3";
};14. What are Text Blocks?
Introduced in Java 15, Text Blocks (""" ... """) provide clean multi-line string literals that automatically manage indentation and strip incidental whitespace, making embedded JSON, SQL, and HTML readable:
String jsonPayload = """
{
"orderId": "%s",
"currency": "USD",
"items": ["book", "laptop"]
}
""".formatted(orderId);15. Explain Records and their use cases.
Introduced in Java 16, a record is a transparent, immutable data carrier. The compiler automatically generates:
private finalfields for all components- Canonical constructor
- Getters (
order.id(), notgetId()) - Idiomatic
equals(),hashCode(), andtoString()
public record OrderDto(String id, BigDecimal total, List<String> items) {
// Compact constructor for validation
public OrderDto {
Objects.requireNonNull(id, "ID cannot be null");
if (total.compareTo(BigDecimal.ZERO) < 0) {
throw new IllegalArgumentException("Total cannot be negative");
}
}
}Records are ideal for API DTOs, Kafka message payloads, and CQRS projection models.
16. What are Sealed Classes?
Introduced in Java 17, Sealed Classes restrict which classes or interfaces may extend or implement them using the sealed and permits keywords:
public sealed interface PaymentStatus permits Authorized, Captured, Declined {}
public final class Authorized implements PaymentStatus {}
public final class Captured implements PaymentStatus {}
public final class Declined implements PaymentStatus {}This gives domain models algebraic data types (ADTs). When pattern matching in a switch, the compiler knows all permitted subtypes and eliminates the need for an unnecessary default: branch.
17. What is Pattern Matching for instanceof?
Java 16 eliminated the redundant boilerplate of checking a type and manually casting it:
// Pre-Java 16:
if (obj instanceof Order) {
Order o = (Order) obj;
o.process();
}
// Java 16+:
if (obj instanceof Order o && o.isEligibleForDiscount()) {
o.applyDiscount();
}18. Record vs Traditional Java Class?
| Dimension | Traditional Class | Java Record |
|---|---|---|
| Mutability | Mutable by default | Strictly immutable (final fields) |
| Inheritance | Can extend any class | Extends java.lang.Record; cannot extend others |
| Boilerplate | Requires Lombok or manual getters/hashcode | 100% compiler-generated in 1 line |
| JPA Entities | Required for Hibernate @Entity (needs proxying & no-arg constructor) | Unsuitable for JPA entities; perfect for DTO projections |
19. What JVM improvements came with Java 17?
- Strong encapsulation of internal JDK packages by default (JEP 403).
- Major throughput and latency optimizations in G1GC.
- Native macOS AArch64 (Apple Silicon M-series) JIT compilation.
- Deprecation of the Security Manager for removal.
Explore modern Java records and sealed types in our Java Records, Enums & Sealed Classes Masterclass and Java 12 to 17 Features Guide.
Part 4: Java 18 to Java 21 LTS
20. What are Virtual Threads?
Introduced as production-ready in Java 21 (Project Loom), Virtual Threads are lightweight threads managed entirely by the Java runtime rather than the operating system.
While traditional platform threads map 1:1 to OS kernel threads, virtual threads use an M:N carrier model: millions of virtual threads run on a small pool of carrier OS threads (sized to the number of CPU cores).
21. Virtual Threads vs Platform Threads?
- Memory Footprint: Platform threads allocate ~1MB of off-heap stack memory at creation. Virtual threads start with an initial stack of just a few hundred bytes allocated directly on the JVM heap that grows and shrinks dynamically.
- Context Switching: Platform threads require kernel-level context switching (2–10 microseconds). Virtual threads unmount and mount in user space (sub-microsecond).
- Scale: A standard server crashes after creating ~4,000 platform threads. A single Java 21 instance easily supports 1,000,000+ virtual threads.
22. How do Virtual Threads improve scalability?
In typical I/O-bound microservices (HTTP calls, database queries, Redis reads), platform threads spend 95% of their lifetime blocked waiting for socket responses.
With Virtual Threads, whenever code performs a blocking I/O operation (e.g., socketRead() or JDBC query), the JVM unmounts the virtual thread from its carrier OS thread. The carrier thread immediately executes other virtual threads. When I/O finishes, the JVM remounts the virtual thread on any available carrier thread.
This restores the simplicity of the synchronous thread-per-request model while matching or exceeding the throughput of complex reactive frameworks (WebFlux / RxJava).
23. What is Structured Concurrency?
Structured Concurrency (Preview in Java 21/22) treats multiple concurrent subtasks running in different threads as a single atomic unit of work, ensuring that parent tasks do not leak orphaned background threads if one child fails:
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Supplier<User> userSubtask = scope.fork(() -> fetchUser(id));
Supplier<Credit> creditSubtask = scope.fork(() -> fetchCredit(id));
scope.join(); // Join both subtasks
scope.throwIfFailed(); // Propagate exception if either subtask fails
return new AccountSummary(userSubtask.get(), creditSubtask.get());
} // Both threads are guaranteed closed upon exiting the block24. What are Scoped Values?
Scoped Values (ScopedValue<T>) provide a modern, thread-safe, immutable alternative to ThreadLocal, specifically designed for Virtual Threads.
Unlike ThreadLocal, which is mutable and carries high memory overhead when inherited by millions of virtual threads, Scoped Values are bound to an execution scope, immutable during execution, and automatically garbage-collected when the scope terminates.
25. Explain Pattern Matching for Switch.
Finalized in Java 21, switch statements and expressions can match against arbitrary types and inspect record components using guard clauses (when):
static String formatResponse(Object response) {
return switch (response) {
case null -> "Empty response";
case String s when s.length() > 100 -> "Long text: " + s.substring(0, 50);
case OrderDto(String id, BigDecimal total, var items) ->
"Order #" + id + " with " + items.size() + " items";
case Number n -> "Numeric response: " + n;
default -> "Unknown type: " + response.toString();
};
}26. What are Sequenced Collections?
Prior to Java 21, getting the first or last element of a collection was frustratingly inconsistent (list.get(0) vs set.iterator().next() vs deque.peekFirst()).
Java 21 introduced SequencedCollection<E>, SequencedSet<E>, and SequencedMap<K, V> providing standardized methods across all ordered collections:
addFirst(e),addLast(e)getFirst(),getLast()removeFirst(),removeLast()reversed(): Returns a reverse-ordered view inO(1)time.
27. What is Generational ZGC?
ZGC originally collected the entire heap uniformly. Java 21 introduced Generational ZGC (-XX:+UseZGC -XX:+ZGenerational), separating the heap into Young and Old generations.
Since the weak generational hypothesis holds true in 99% of backend workloads (most objects die young), Generational ZGC collects short-lived transient allocations far more frequently, preventing allocation stalls while maintaining sub-millisecond pause times on terabyte-scale heaps.
Master Project Loom and high-scale concurrency in our Java 21 Virtual Threads Architecture Course and Sequenced Collections Deep Dive.
Part 5: Advanced Java & JVM Internals
28. synchronized vs ReentrantLock?
| Dimension | synchronized | ReentrantLock |
|---|---|---|
| Type | JVM built-in language keyword | Class in java.util.concurrent.locks |
| Acquisition | Implicit acquire and release | Explicit lock() and mandatory finally { unlock(); } |
| Fairness | Unfair only | Configurable fair/unfair policy |
| Interruptibility | Cannot interrupt a thread waiting for lock | lockInterruptibly() allows thread abort |
| Timed Try | No | tryLock(100, TimeUnit.MILLISECONDS) |
| Condition Queues | 1 wait set per object (wait/notify) | Multiple condition variables per lock (Condition.await()) |
29. volatile vs AtomicInteger?
volatile: Guarantees visibility (reads/writes bypass CPU L1/L2 caches and flush to main memory) and ordering (prevents instruction reordering). It does NOT guarantee atomicity for compound actions likecount++(which is a 3-step read-modify-write operation).AtomicInteger: Guarantees visibility and atomicity using non-blocking hardware Compare-And-Swap (CAS) machine instructions (lock cmpxchg).
30. How does ConcurrentHashMap work internally?
In modern Java (Java 8+):
- Lock-Free Reads: Reads (
get()) require zero locks. Hash bucket node references and values are declaredvolatile, allowing concurrent reads without blocking. - Synchronized Bucket Level Writes: Unlike Java 7's 16 ReentrantLock Segment arrays, Java 8+ uses CAS on empty buckets (
casTabAt). If a collision occurs, it locks only the individual head node of that bucket viasynchronized(node). - Treeification: When a bucket exceeds 8 entries (and total capacity >= 64), it converts to a Red-Black Tree to bound worst-case search to
O(log n).
31. ExecutorService vs ForkJoinPool?
ExecutorService(e.g.,ThreadPoolExecutor): Uses a single shared blocking work queue. Worker threads compete for tasks from this queue. Ideal for independent, homogeneous, coarse-grained asynchronous I/O tasks.ForkJoinPool: Designed for compute-heavy divide-and-conquer parallelism. Every worker thread has its own double-ended queue (deque). It implements work-stealing: idle threads steal pending tasks from the tail of busy threads' deques, maximizing multi-core CPU cache utilization. It powers the parallel Stream API and CompletableFuture.
32. Explain Deadlock, Starvation, and Race Conditions.
- Deadlock: Two or more threads are permanently blocked, each holding a lock that the other needs (Thread 1 holds lock
L1waits forL2; Thread 2 holds lockL2waits forL1). - Starvation: A runnable thread is perpetually denied CPU time or lock acquisition because greedy or higher-priority threads dominate the monitor.
- Race Condition: Program correctness depends on the non-deterministic relative execution timing of concurrent threads (e.g., lost updates).
33. How does Garbage Collection work?
The JVM heap is split into:
- Young Generation: Eden space + two Survivor spaces (S0/S1). New objects allocate in Eden. When Eden fills, a fast Minor GC copies surviving objects to a Survivor space.
- Tenured / Old Generation: Objects that survive multiple GC cycles (default threshold: 15) promote to Old Gen. When Old Gen reaches capacity, a Major/Full GC compacts the space.
GC identifies live objects by tracing reference chains from GC Roots (active thread stacks, static variables, JNI references). Any object unreachable from GC roots is marked for sweep.
34. G1 GC vs ZGC?
- G1 GC (Garbage-First): Partitions the heap into thousands of equal-sized regions (1MB–32MB). Dynamically assigns regions to Young or Old. Reclaims regions with the most garbage first within a tunable pause target (e.g.,
-XX:MaxGCPauseMillis=100). - ZGC (Zero Garbage Collector): A scalable low-latency collector where pause times do not scale with heap size. Performs marking, compaction, and reference processing concurrently while Java threads continue running using colored pointers and load barriers.
35. Explain JVM memory areas.
- Heap: Shared across all threads; holds all instantiated class instances and arrays.
- JVM Stack: Private to each thread; holds method execution frames, primitive local variables, and object reference pointers.
- Metaspace (Off-Heap): Replaced PermGen in Java 8; stores class metadata, method bytecode, and the runtime constant pool in native OS memory.
- Program Counter (PC) Register: Contains the memory address of the JVM instruction currently being executed by the thread.
- Native Method Stack: Supports execution of C/C++ native code via JNI.
Explore deep memory profiling and garbage collection tuning in our JVM Heap, Stack & Metaspace Guide and Garbage Collection Architecture Course.
Part 6: Scenario-Based Production Questions
36. How would you troubleshoot high CPU usage in a Java application?
Follow this systematic 4-step production triage:
- Identify the culprit OS thread ID using Linux CLI:
bash
top -H -p <jvm_pid> # Find thread with highest %CPU (e.g., TID 24115) # Convert decimal TID to hexadecimal: printf '%x\n' 24115 # Outputs: 5e33 - Capture a JVM Thread Dump:
bash
jcmd <jvm_pid> Thread.print > threaddump.txt - Correlate the Hex Thread ID (
nid=0x5e33): Search fornid=0x5e33inthreaddump.txtto find the exact class and line number burning CPU cycles (e.g., an infinitewhileloop, regex backtracking, or hashmap collision scan). - Profile CPU Execution with async-profiler: Generate an interactive SVG FlameGraph to visualize CPU cycles across your call stack.
37. How would you investigate frequent GC pauses?
- Enable GC logging:
-Xlog:gc*,gc+phases=info:file=gc.log:time,uptime,pid. - Inspect GC logs with GCViewer or upload to GCEasy to determine pause frequency and STW phase durations.
- Check if Young Gen is undersized, forcing short-lived transient request payloads into Old Gen.
- Take a heap dump (
jcmd <pid> GC.heap_dump /tmp/dump.hprof) and inspect the Dominator Tree in Eclipse MAT to locate memory bloat.
38. How would you optimize memory consumption?
- Replace Boxed Collections: Switch from
List<Long>to primitive collections (fastutil, Eclipse Collections). - Adopt Java Records & Compact Strings: Leverage Java's default UTF-16 vs Latin-1 compact string representation.
- Tune Off-Heap Memory: Configure Netty direct buffer bounds (
-XX:MaxDirectMemorySize). - Eliminate Deep DTO Duplication: Stream database results directly using JPA projections or jOOQ instead of instantiating hundreds of thousands of intermediate entity graphs.
39. How would you handle thousands of concurrent API requests?
- Adopt Java 21 Virtual Threads: Configure embedded Tomcat in Spring Boot (
spring.threads.virtual.enabled=true) to process requests on lightweight virtual threads without pool starvation. - Protect Downstream Databases: Virtual threads can overwhelm databases; bound database concurrency using a
Semaphoreor appropriately sized HikariCP pool. - Implement Rate Limiting & Backpressure: Enforce token-bucket rate limiting via Redis or API gateways to shed load before saturating JVM memory.
- Non-Blocking Caching: Add a distributed Redis cache layer with cache stampede protection.
40. How would you migrate an enterprise application from Java 8 to Java 21?
A structured migration blueprint:
- Step 1: Dependency & Build Audit: Run OpenRewrite or Maven dependency plugins to upgrade Spring Boot to 3.x, Hibernate to 6.x, and upgrade build plugins (Maven Compiler, Surefire) to Java 21 compatible releases.
- Step 2: Address Removed & Encapsulated APIs:
- Replace removed Java EE packages (
javax.*→jakarta.*). - Audit code for internal reflection calls blocked by JPMS strong encapsulation (
--add-opensflags as temporary workarounds).
- Replace removed Java EE packages (
- Step 3: Update JVM Runtime Flags: Remove legacy flags (e.g.,
-XX:+UseConcMarkSweepGC,-XX:MaxPermSize) and configure modern G1GC or Generational ZGC. - Step 4: Enable Modern Features Incrementally: Refactor boilerplate classes to Records, replace
synchronizedwith virtual thread-friendly constructs, and enablespring.threads.virtual.enabled=true.
For a full breakdown of migration pitfalls and interview favorites, read our Java Version Interview Favourites Guide.
Continue Your Journey with Veltoryx
Preparing for technical leadership roles requires mastering the full stack of modern backend engineering.
Explore our comprehensive interactive curriculum:
- Java Core, Concurrency & Loom Masterclass
- Spring Boot & Microservices Production Guide
- High-Level & Low-Level System Design
- WhatsApp & Swiggy Case Studies
Level up your engineering career with interactive algorithmic visualizers, real-world case studies, and complete architectural blueprints:
Explore Free Developer Tools & Interactive Tracks
Test data structures, format code, and master system design on the Veltoryx platform.
Related Engineering Articles
Java Backend Developer 1st Round Interview: 20 Questions Being Asked in 2026
A battle-tested guide to the top 20 core Java, JVM, Spring Boot, JPA, and distributed systems questions asked in senior first-round technical interviews in 2026—with code examples, root causes, and production fixes.
Vivek Adarsh
Nov 5, 2026
35 Java Streams API Questions for SDE-2 Interviews
The definitive 2026 guide to 35 essential Java Streams coding and conceptual interview questions for SDE-2 and Senior Backend roles—with production code, edge cases, and collector architectures.
Vivek Adarsh
Nov 5, 2026
Java DSA Interview – Complete Methods & Syntax Cheat Sheet
The ultimate quick-reference cheat sheet for Java DSA coding interviews — covering essential Java 8+ syntax, collection methods, and LeetCode problem-solving patterns.
Vivek Adarsh
Nov 24, 2026