Prev Next

Java / Java 21 Interview Questions

1. What is Java 21 and why is it a significant release? 2. What are Virtual Threads in Java 21 and how do they differ from Platform Threads? 3. How does Pattern Matching for switch work in Java 21? 4. What are Record Patterns in Java 21 and how do they enable deconstruction? 5. What are Sequenced Collections in Java 21? 6. What are sealed classes and interfaces in Java and why are they important for pattern matching? 7. What are Java Records and what do they automatically generate? 8. What are Text Blocks in Java and how do you use them? 9. What is Structured Concurrency in Java 21 and what problem does it solve? 10. What are Scoped Values in Java 21 and how do they differ from ThreadLocal? 11. What is Generational ZGC in Java 21 and why does it improve upon the original ZGC? 12. What important String methods were added from Java 11 through Java 21? 13. What is 'var' in Java and what are its limitations? 14. What are switch expressions in Java and how do they differ from switch statements? 15. How does pattern matching for instanceof work in Java 16+? 16. What Stream API improvements were introduced in Java 9 through Java 21? 17. How has Optional been improved and how should it be used correctly? 18. How does CompletableFuture work in Java and how does it relate to virtual threads? 19. What does the 'volatile' keyword guarantee in Java's memory model? 20. What are the immutable collection factory methods introduced in Java 9? 21. What are functional interfaces in Java and how are lambdas related to them? 22. What are the most important Collectors and how do you write custom ones? 23. What are Unnamed Classes and Instance Main Methods in Java 21 (Preview)? 24. What improvements were made to NullPointerException messages in Java 14? 25. How does type erasure affect instanceof checks with generics in Java? 26. What are the differences between 'synchronized' and ReentrantLock in Java? 27. What are the key classes in the java.time package and when do you use each? 28. What garbage collectors are available in Java 21 and how do you choose between them? 29. What is the Java Platform Module System (JPMS) and when should you use it? 30. What are String Templates in Java 21 (Preview) and how do they improve string interpolation? 31. What are the contracts for equals(), hashCode(), and Comparable in Java? 32. What are the best practices for exception handling in Java? 33. Why is immutability important in Java and how do you implement it correctly? 34. What are default and static methods in Java interfaces? 35. How does HashMap work internally in Java? 36. How do virtual threads compare to reactive programming (Project Reactor / RxJava)? 37. What is the Java 11 HttpClient and how do you use it for HTTP requests? 38. What capabilities do Java enums have beyond simple named constants? 39. What are the java.util.concurrent.atomic classes and how do they work? 40. How does Java Reflection work and what are its performance implications? 41. What are Unnamed Patterns and Variables in Java 21 (Preview) and how do they reduce boilerplate? 42. When should you use StructuredTaskScope instead of CompletableFuture in Java 21? 43. What major APIs were removed between Java 17 and Java 21? 44. What are the most important JVM flags for tuning Java 21 application performance? 45. What are the key steps and pitfalls when migrating an application to Java 21? 46. How do Spring 7 and Spring Boot 4 optimize thread usage compared to older blocking models?

1. What is Java 21 and why is it a significant release?

Java 21, released in September 2023, is a Long-Term Support (LTS) release of the Java platform, making it the next major production-grade baseline after Java 17. It is the first LTS release to deliver Virtual Threads as a stable feature (Project Loom), Record Patterns , Pattern Matching for switc...

Read full answer

2. What are Virtual Threads in Java 21 and how do they differ from Platform Threads?

Virtual Threads (JEP 444) are lightweight threads managed by the JVM rather than the operating system. A platform (OS) thread maps 1:1 to a kernel thread and consumes roughly 1–2 MB of stack memory each, limiting practical concurrency to a few thousand threads per JVM. Virtual threads are multipl...

Read full answer

3. How does Pattern Matching for switch work in Java 21?

JEP 441 finalises pattern matching in switch expressions and statements, extending the type-test patterns introduced in Java 16 ( instanceof ) to the full switch construct. It eliminates long chains of if-else instanceof casts and brings exhaustiveness checking to the compiler. sealed interface S...

Read full answer

4. What are Record Patterns in Java 21 and how do they enable deconstruction?

JEP 440 finalises record patterns, which extend the type-test pattern ( instanceof Point p ) to simultaneously match a record's type and destructure its components into named variables. This eliminates the boilerplate of calling accessor methods after a type check. record Point(int x, int y) {} r...

Read full answer

5. What are Sequenced Collections in Java 21?

JEP 431 introduces three new interfaces — SequencedCollection , SequencedSet , and SequencedMap — to the collections hierarchy. Before Java 21 there was no unified API to access the first or last element of a collection, or to iterate in reverse order; each concrete class had its own ad-hoc appro...

Read full answer

6. What are sealed classes and interfaces in Java and why are they important for pattern matching?

Sealed classes (JEP 409, finalised in Java 17, heavily used with Java 21 pattern matching) restrict which classes can extend or implement them. You declare the permitted subtypes explicitly in a permits clause, giving the compiler a closed world of possibilities. // Sealed interface — only these ...

Read full answer

7. What are Java Records and what do they automatically generate?

Records (JEP 395, finalised in Java 16) are a concise syntax for declaring immutable data-carrier classes. A single record declaration replaces a full class with private final fields, a canonical constructor, accessors, equals() , hashCode() , and toString() . // Declaration — the header defines ...

Read full answer

8. What are Text Blocks in Java and how do you use them?

Text Blocks (JEP 378, finalised in Java 15) provide a multi-line string literal that preserves formatting without escape sequences. They are delimited by """ and the content starts on the line after the opening delimiter. // Traditional string — escape-heavy String json = "{\n" + " \"name\": \"Al...

Read full answer

9. What is Structured Concurrency in Java 21 and what problem does it solve?

Structured Concurrency (JEP 453, second preview in Java 21) is an API — built on StructuredTaskScope — that treats a group of concurrent subtasks as a single unit of work whose lifetime is scoped to the code block that created them. It solves the problem of unreliable cancellation, lost exception...

Read full answer

10. What are Scoped Values in Java 21 and how do they differ from ThreadLocal?

Scoped Values (JEP 446, first preview in Java 21) provide an immutable, bounded alternative to ThreadLocal designed specifically for virtual threads. A ScopedValue holds a value for the duration of a bounded scope (a ScopedValue.where(...).run(...) block) and is automatically removed when the sco...

Read full answer

11. What is Generational ZGC in Java 21 and why does it improve upon the original ZGC?

JEP 439 finalises Generational ZGC, which extends the existing low-latency Z Garbage Collector with separate young and old generations. Classic ZGC (introduced in Java 11) collects all live objects on every GC cycle, which is thorough but wastes CPU on long-lived objects that will not be collecte...

Read full answer

12. What important String methods were added from Java 11 through Java 21?

The String class received significant API improvements across several Java releases. Knowing the version they arrived in is common interview territory. Key String Methods (Java 11–21) Method Since Purpose isBlank() 11 Returns true if string is empty or contains only whitespace strip() / stripLead...

Read full answer

13. What is 'var' in Java and what are its limitations?

var (JEP 286, Java 10) introduces local variable type inference. The compiler infers the type from the initialiser on the right-hand side; you do not need to write the type explicitly. It is not a dynamic type — the variable is still strongly typed at compile time; var is just syntactic sugar. //...

Read full answer

14. What are switch expressions in Java and how do they differ from switch statements?

Switch expressions (JEP 361, finalised in Java 14) make switch a value-producing expression rather than only a control-flow statement. They use the arrow ( -> ) syntax and require exhaustiveness. Switch Statement vs Switch Expression Aspect Switch Statement Switch Expression Produces a value No Y...

Read full answer

15. How does pattern matching for instanceof work in Java 16+?

JEP 394 (finalised in Java 16) extends the instanceof operator with a type pattern that both tests the type and binds a typed local variable in a single expression, eliminating the explicit cast that always followed a traditional instanceof check. // Traditional — test + cast (redundant, error-pr...

Read full answer

16. What Stream API improvements were introduced in Java 9 through Java 21?

The Stream API has been incrementally enhanced since Java 9. Knowing which methods are available and when they arrived is frequently tested. Stream API Additions (Java 9–21) Method Since Description takeWhile(Predicate) 9 Takes elements while predicate is true, then stops dropWhile(Predicate) 9 D...

Read full answer

17. How has Optional been improved and how should it be used correctly?

Optional (Java 8) is a container for a value that may or may not be present. It is designed to be a return type that makes the absence of a value explicit in the API contract, not a replacement for null in all contexts. Key Optional methods Method Since Purpose of(T) / ofNullable(T) / empty() ...

Read full answer

18. How does CompletableFuture work in Java and how does it relate to virtual threads?

CompletableFuture (Java 8) provides composable asynchronous computation pipelines. It lets you chain transformations ( thenApply ), combinations ( thenCombine ), and error handlers ( exceptionally ) without blocking threads. // Basic async computation CompletableFuture future = CompletableFutu...

Read full answer

19. What does the 'volatile' keyword guarantee in Java's memory model?

The volatile keyword provides two guarantees in the Java Memory Model (JMM): visibility and ordering . Visibility : A write to a volatile variable is immediately flushed to main memory, and a read of a volatile variable always reads from main memory — not from a CPU cache. This prevents a thread ...

Read full answer

20. What are the immutable collection factory methods introduced in Java 9?

Java 9 (JEP 269) introduced convenient static factory methods on List , Set , and Map for creating small, immutable collections without the verbosity of Arrays.asList() or Collections.unmodifiableList() . // Java 9+ — concise and immutable List list = List.of("a", "b", "c"); // immutable Set set ...

Read full answer

21. What are functional interfaces in Java and how are lambdas related to them?

A functional interface is an interface with exactly one abstract method (SAM — Single Abstract Method). The @FunctionalInterface annotation is optional but recommended — it causes the compiler to enforce the single-abstract-method rule. Lambdas and method references provide implementations for fu...

Read full answer

22. What are the most important Collectors and how do you write custom ones?

Collectors define how a terminal collect() operation assembles the stream elements. java.util.stream.Collectors provides ~40 factory methods; the most frequently used in interviews are: import static java.util.stream.Collectors.*; // Grouping Map > byCity = people.stream().collect(groupingBy(Pers...

Read full answer

23. What are Unnamed Classes and Instance Main Methods in Java 21 (Preview)?

JEP 445 (preview in Java 21) removes much of the ceremony required to write a simple Java program. It targets learning, scripting, and small utilities — not production application structure. // Traditional Hello World — requires class declaration, static, String[] args public class HelloWorld { p...

Read full answer

24. What improvements were made to NullPointerException messages in Java 14?

JEP 358 (Java 14) enabled helpful NullPointerException messages that precisely identify which variable or expression was null, rather than just the line number and a generic message. This was one of the most immediately useful quality-of-life improvements in recent Java history. // Before Java 14...

Read full answer

25. How does type erasure affect instanceof checks with generics in Java?

Type erasure means generic type parameters are removed at compile time, leaving only the raw type at runtime. This has direct implications for instanceof checks. // Cannot check parameterised generic types at runtime List strings = List.of("a", "b"); if (strings instanceof List) &...

Read full answer

26. What are the differences between 'synchronized' and ReentrantLock in Java?

synchronized is Java's built-in intrinsic lock mechanism. ReentrantLock (in java.util.concurrent.locks ) provides the same mutual-exclusion guarantee but with more capabilities at the cost of more verbose code. synchronized vs ReentrantLock Feature synchronized ReentrantLock Lock acquisition Impl...

Read full answer

27. What are the key classes in the java.time package and when do you use each?

The java.time package (Java 8, JSR 310) replaces the problematic java.util.Date and java.util.Calendar classes. All classes are immutable and thread-safe by design. Core java.time classes Class Represents Example LocalDate Date without time or timezone 2024-03-15 LocalTime Time without date or ti...

Read full answer

28. What garbage collectors are available in Java 21 and how do you choose between them?

Java 21 ships four major garbage collectors, each optimised for different trade-off points on the throughput-vs-latency spectrum. GC Comparison in Java 21 GC Flag Pause target Throughput Best for Serial GC -XX:+UseSerialGC Not optimised — STW Low Single-core, small heap (<100 MB) Parallel GC -XX:...

Read full answer

29. What is the Java Platform Module System (JPMS) and when should you use it?

JPMS (Project Jigsaw, JEP 261, Java 9) introduces the concept of modules — named, versioned groups of packages with explicit dependency declarations and access control. It solves the classpath hell problem (no visibility into what JARs exist or what they expose) and improves security by allowing ...

Read full answer

30. What are String Templates in Java 21 (Preview) and how do they improve string interpolation?

JEP 430 introduces String Templates as a preview feature in Java 21. They provide type-safe string interpolation via template processors — a safer alternative to string concatenation and String.format() that prevents injection vulnerabilities by separating the template structure from the values. ...

Read full answer

31. What are the contracts for equals(), hashCode(), and Comparable in Java?

These three methods have formal contracts that must be maintained for code to work correctly with collections, sorting, and data structures. // equals() contract: // 1. Reflexive: x.equals(x) == true // 2. Symmetric: x.equals(y) == y.equals(x) // 3. Transitive: x.equals(y) && y.equals(z) => x.equ...

Read full answer

32. What are the best practices for exception handling in Java?

Exception handling design is a common interview discussion topic. Java distinguishes checked exceptions (must be declared or caught — compiler enforces), unchecked (RuntimeException subclasses), and errors (JVM-level, not catchable in normal code). // 1. Prefer specific exceptions over general on...

Read full answer

33. Why is immutability important in Java and how do you implement it correctly?

An immutable object's state cannot change after construction. Immutable objects are inherently thread-safe, can be freely shared without copying, make better HashMap keys, and simplify reasoning about code because no method can have hidden side effects on them. // Building an immutable class corr...

Read full answer

34. What are default and static methods in Java interfaces?

Java 8 added default and static methods to interfaces, fundamentally changing the relationship between interfaces and abstract classes. interface Validator { // Abstract method — implementors must provide boolean isValid(T value); // Default method — provided implementation, can be overridden def...

Read full answer

35. How does HashMap work internally in Java?

Understanding HashMap internals — hashing, buckets, collisions, resizing, and treeification — is one of the most commonly asked Java interview topics at mid-to-senior level. // Internal structure: // - Node [] table — array of buckets (initially null, lazily allocated) // - Default capacity: 16, ...

Read full answer

36. How do virtual threads compare to reactive programming (Project Reactor / RxJava)?

Both virtual threads (Java 21) and reactive frameworks solve the same underlying problem: how to serve many concurrent I/O-bound requests without blocking OS threads, which are expensive. They solve it very differently. Reactive vs Virtual Threads Aspect Reactive (Reactor/RxJava) Virtual Threads ...

Read full answer

37. What is the Java 11 HttpClient and how do you use it for HTTP requests?

The java.net.http.HttpClient (JEP 321, finalised in Java 11) is a modern, non-blocking HTTP client that supports HTTP/1.1 and HTTP/2, WebSockets, synchronous and asynchronous request modes, and streaming. It replaces the antiquated HttpURLConnection . import java.net.http.*; import java.net.URI; ...

Read full answer

38. What capabilities do Java enums have beyond simple named constants?

Java enums are full-fledged classes that happen to have a fixed number of instances. This makes them far more powerful than C-style enums and eliminates entire categories of bugs that arise from using int constants. public enum Planet { MERCURY(3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), E...

Read full answer

39. What are the java.util.concurrent.atomic classes and how do they work?

The java.util.concurrent.atomic package provides lock-free, thread-safe single-variable operations using CPU-level Compare-And-Swap (CAS) instructions. They are faster than synchronized blocks for single-variable updates because they avoid locking entirely. // AtomicInteger — counter safe for use...

Read full answer

40. How does Java Reflection work and what are its performance implications?

Reflection allows programs to inspect and manipulate classes, methods, fields, constructors, and annotations at runtime — without knowing them at compile time. It powers frameworks like Spring (dependency injection), Hibernate (ORM), JUnit (test discovery), and Jackson (JSON serialisation). impor...

Read full answer

41. What are Unnamed Patterns and Variables in Java 21 (Preview) and how do they reduce boilerplate?

JEP 443 (preview in Java 21) introduces the underscore _ as a special token meaning 'I don't care about this value'. It can be used as an unnamed variable in catch blocks, try-with-resources, enhanced for loops, and lambda parameters — and as an unnamed pattern component in record patterns. // --...

Read full answer

42. When should you use StructuredTaskScope instead of CompletableFuture in Java 21?

Both APIs manage concurrent asynchronous work, but they have different designs, guarantees, and ideal use cases. Java 21 introduces StructuredTaskScope as the preferred model when running on virtual threads. CompletableFuture vs StructuredTaskScope Aspect CompletableFuture StructuredTaskScope API...

Read full answer

43. What major APIs were removed between Java 17 and Java 21?

Java 21 continues the cleanup of APIs that were deprecated in earlier releases. Understanding what was removed helps interviewers assess whether a candidate's Java knowledge is current. Removals and Deprecations (Java 17–21) API/Feature Deprecated Removed Replacement Security Manager Java 17 Java...

Read full answer

44. What are the most important JVM flags for tuning Java 21 application performance?

Understanding key JVM flags distinguishes senior engineers from juniors. Here are the flags that matter most for Java 21 production deployments. Essential JVM Flags Flag Category Purpose -Xms / -Xmx Memory Initial / max heap size. Set equal to avoid resizing pauses -XX:+UseZGC GC Enable ZGC (Gene...

Read full answer

45. What are the key steps and pitfalls when migrating an application to Java 21?

Migrating from Java 8/11/17 to Java 21 requires attention to removed APIs, module system access restrictions, and the opportunity to adopt new features incrementally. // Step 1: Compile with Java 21 — fix deprecation warnings // javac --release 21 -Xlint:deprecation src/**/*.java // Step 2: Run w...

Read full answer

46. How do Spring 7 and Spring Boot 4 optimize thread usage compared to older blocking models?

Older versions of Spring MVC scaled using a rigid "one-request-per-thread" blocking architecture tied to expensive platform (OS) threads. Spring 7 builds on top of modern Java baselines to offer native, out-of-the-box optimization for Virtual Threads. This allows applications to process millions ...

Read full answer

«
»

Comments & Discussions