Java 7 Interview Questions
- What are the key features introduced in Java 7?
- Explain the
try-with-resourcesstatement in Java 7. - What is the
AutoCloseableinterface, and how does it relate to try-with-resources? - Explain multi-catch exception handling in Java 7.
- What is the diamond operator in Java 7, and how does it simplify generic code?
- Explain the "String in switch" feature introduced in Java 7.
- What is NIO.2, and what problems does it solve in Java 7?
- Explain the
Pathinterface introduced in Java 7's NIO.2. - How do you use the
Filesclass for common file operations in Java 7? - What is the
WatchServiceAPI in Java 7, and how is it used? - Explain the Fork/Join framework introduced in Java 7.
- What is the difference between
RecursiveTaskandRecursiveActionin the Fork/Join framework? - How does
ForkJoinPooldiffer from a regularExecutorService? - What are binary literals in Java 7?
- Explain the use of underscores in numeric literals in Java 7.
- What is the
invokedynamicinstruction, and why was it added in Java 7? - Explain the
Objectsutility class introduced in Java 7. - What are suppressed exceptions in Java 7's try-with-resources?
- What is the purpose of the
@SafeVarargsannotation introduced in Java 7? - Explain the concurrency enhancements in Java 7, such as
PhaserandTransferQueue. - What is the G1 (Garbage-First) garbage collector introduced in Java 7?
- How does catching multiple exception types in one catch block improve code compared to Java 6?
- What improvements did Java 7 NIO.2 bring to copying and moving files?
- What are the key differences between Java 6 and Java 7?
- What are the limitations of Java 7 compared to later versions like Java 8?
Java 11 Interview Questions
- What are the key features introduced in Java 11?
- Explain the use of
varkeyword introduced in Java 10 and how it is used in Java 11. - What is the
HttpClientAPI introduced in Java 11? - How does the new
HttpClientAPI compare to the previousHttpURLConnection? - Explain the use of the
isBlank()method in Java 11. - What is the
repeat()method introduced in Java 11? - How do you use the
lines()method on a string in Java 11? - What is the
strip()method in Java 11, and how is it different fromtrim()? - Explain the new
files.mismatch()method introduced in Java 11. - What are the new options available in
javacin Java 11? - Explain the
Nest-Based Access Controlin Java 11. - What is the significance of the
varkeyword in local variables in Java 11? - What are the key differences between Java 8 and Java 11?
- What is the new Epsilon Garbage Collector introduced in Java 11?
- How does the Epsilon Garbage Collector work?
- Explain the use of
optional.isEmpty()method in Java 11. - What is the significance of the
ZGC(Z Garbage Collector) introduced in Java 11? - Explain the
Flight Recorderfeature introduced in Java 11. - What is the
launch single-file source-code programsfeature in Java 11? - How does Java 11 support running source files directly without compilation?
- What is the
String.lines()method in Java 11, and how is it used? - What is the difference between
stripLeading()andstripTrailing()in Java 11? - How do you perform file I/O operations using new methods in Java 11?
- What are the new methods added to the
Optionalclass in Java 11? - Explain the concept of
Lambda Parameter Type Inferencein Java 11. - What is the purpose of the new
Handoffmethod in Java 11'sCompletableFuture? - How does the
Stream.ofNullable()method introduced in Java 9 enhance stream processing in Java 11? - What are the new changes introduced in the
java.util.regexpackage in Java 11? - Explain the concept of
Pattern Matching for instanceofintroduced in Java 11.
Java 17 Interview Questions
- What are the key features introduced in Java 17?
- Explain the concept of Sealed Classes in Java 17.
- How do you use Sealed Classes in Java 17?
- What are the benefits of using Sealed Classes in Java 17?
- Explain the concept of Pattern Matching for
switchintroduced in Java 17. - How does Pattern Matching for
switchimprove code readability in Java 17? - What is the purpose of the new
JEP 356: Enhanced Pseudo-Random Number Generatorsin Java 17? - How do the new random number generator interfaces work in Java 17?
- Explain the new
JEP 382: New macOS Rendering Pipelinein Java 17. - What is the
JEP 409: Sealed Classesin Java 17, and how is it implemented? - How do
JEP 356andJEP 409enhance the security and performance of Java applications? - What are the new enhancements to
ZGC(Z Garbage Collector) in Java 17? - Explain the new
JEP 403: Strong Encapsulation by Defaultin Java 17. - How does strong encapsulation impact modularity in Java 17?
- What are the improvements in
JEP 356: Enhanced Pseudo-Random Number Generators? - How does the new
JEP 356impact cryptography in Java 17? - What is the
JEP 415: Context-Specific Deserialization Filtersin Java 17? - How do context-specific deserialization filters enhance security in Java 17?
- What are the new
Foreign Function & Memory APIpreview features in Java 17? - How does the
Foreign Function & Memory APIenhance interoperability in Java 17? - Explain the improvements in
JEP 381: Remove the Solaris and SPARC Portsin Java 17. - What is the impact of removing the Solaris and SPARC ports in Java 17?
- What is
JEP 412: Foreign Function & Memory API (Incubator)in Java 17? - How does
JEP 412support better performance in native code integration? - What is the
JEP 306: Restore Always-Strict Floating-Point Semanticsin Java 17? - Explain the significance of
always-strict floating-point semanticsin Java 17. - What is the new
JEP 356API, and how does it differ from the older random number generator APIs? - How do you use the enhanced switch statement in Java 17?
- What are the changes to the
java.util.regexpackage in Java 17? - Explain the improvements in pattern matching introduced in Java 17.
- What is the new
JEP 403: Strong Encapsulation? How does it change the module system? - How does Java 17 handle pattern matching for instance in switch cases?
- What are the significant changes in the garbage collection mechanism in Java 17?
- Explain the use of
instanceofpattern matching in Java 17. - How do Sealed Classes compare to traditional inheritance models in Java 17?
- What are the new features in text blocks introduced in Java 17?
- Explain the enhanced
Recordclass introduced in Java 17. - What are the advantages of using the
Recordclass over traditional POJOs? - How does Java 17 improve the performance of the JVM?
- What is the significance of
JEP 306: Restore Always-Strict Floating-Point Semanticsin Java 17? - What are the most critical changes in the Java language syntax in Java 17?
Java 21 Interview Questions
- What are the key features introduced in Java 21?
- Explain Virtual Threads introduced in Java 21 (
JEP 444). - What is the difference between virtual threads and platform threads?
- Explain Structured Concurrency in Java 21 (
JEP 453, Preview). - What is Pattern Matching for
switchin Java 21 (JEP 441), and how is it finalized? - Explain Record Patterns in Java 21 (
JEP 440). - How do nested record patterns work? Provide an example.
- What are Sequenced Collections introduced in Java 21 (
JEP 431)? - What new methods do Sequenced Collections add, and why were they needed?
- Explain String Templates introduced in Java 21 (
JEP 430, Preview). - What are Scoped Values in Java 21 (
JEP 446, Preview), and how do they differ fromThreadLocal? - Explain Generational ZGC introduced in Java 21 (
JEP 439). - What is the Key Encapsulation Mechanism API introduced in Java 21 (
JEP 452)? - Explain Unnamed Patterns and Variables introduced in Java 21 (
JEP 443, Preview). - What is the purpose of
JEP 451: Prepare to Disallow the Dynamic Loading of Agents? - Why is Java 21 significant as an LTS release?
- How do virtual threads improve throughput for I/O-bound applications?
- What is thread "pinning," and why is it a limitation of virtual threads?
- How does structured concurrency improve error handling and cancellation compared to raw
ExecutorServiceusage? - How do guarded patterns (
whenclauses) work in switch pattern matching in Java 21? - What is the significance of exhaustiveness checking in switch pattern matching over sealed types?
- What does the
reversed()method on a Sequenced Collection return? - What are the key differences between Java 17 and Java 21?
- How would you migrate a thread-per-request server to use virtual threads in Java 21?
- What should you consider before adopting Java 21 in production?
1. What are the key features introduced in Java 7?
Java 7 (also known as Project Coin/Dolphin) introduced several key features:
- try-with-resources statement
- Multi-catch exception handling
- Diamond operator for generics
- Strings in switch statements
- NIO.2 (new file I/O with Path, Files, WatchService)
- Fork/Join framework for parallel computation
- Binary literals and underscores in numeric literals
- invokedynamic JVM instruction for dynamic languages
- G1 garbage collector (available as an option)
2. Explain the try-with-resources statement in Java 7.
try-with-resources is a special try statement that automatically closes any resource declared in its parentheses once the block finishes, whether normally or via an exception. Any resource used must implement AutoCloseable, and the JVM guarantees close() is called, removing the need for a manual finally block. For example:
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(br.readLine());
}
3. What is the AutoCloseable interface, and how does it relate to try-with-resources?
AutoCloseable is an interface with a single method, close(), that a class implements to release resources such as file handles, sockets, or database connections. Any object that implements AutoCloseable (or the more restrictive Closeable) can be declared inside a try-with-resources statement, and the runtime calls close() automatically when the block exits.
4. Explain multi-catch exception handling in Java 7.
Multi-catch lets a single catch block handle several exception types using the pipe (|) operator, avoiding duplicated handler code. For example:
try {
process();
} catch (IOException | SQLException ex) {
logger.error("Operation failed", ex);
}
The compiler still performs exhaustive type checking, and the caught variable is implicitly final.
5. What is the diamond operator in Java 7, and how does it simplify generic code?
The diamond operator (<>) lets the compiler infer generic type arguments on the right-hand side of an assignment from the declared type on the left, so you no longer repeat the type parameter. For example, Map<String, List<Integer>> map = new HashMap<>(); replaces the more verbose new HashMap<String, List<Integer>>().
6. Explain the "String in switch" feature introduced in Java 7.
Java 7 allows String values as the selector expression in a switch statement, so you can branch on a string directly instead of using a chain of if/else with equals(). Internally the compiler translates the string switch into a hash-based lookup plus an equality check, so it still relies on hashCode() and equals().
7. What is NIO.2, and what problems does it solve in Java 7?
NIO.2 (New I/O 2, delivered under java.nio.file) is a complete overhaul of file system access that replaces the limited, exception-poor java.io.File API. It adds the Path interface, the Files utility class, symbolic link support, better exception reporting, directory-tree walking, and a file-change notification API (WatchService), making file handling more robust, portable, and expressive.
8. Explain the Path interface introduced in Java 7's NIO.2.
Path represents a hierarchical file system location (similar to but more capable than File). It is created via Paths.get() or FileSystems.getDefault(), and supports operations like resolving, normalizing, and comparing paths independent of any actual I/O:
Path path = Paths.get("/data", "reports", "2026.csv");
System.out.println(path.getFileName());
9. How do you use the Files class for common file operations in Java 7?
Files is a static utility class with methods that operate on Path objects, such as Files.copy(), Files.move(), Files.delete(), Files.exists(), Files.readAllBytes(), and Files.walk(). It centralizes file operations that previously required verbose stream handling.
Files.copy(Paths.get("source.txt"), Paths.get("dest.txt"), StandardCopyOption.REPLACE_EXISTING);
10. What is the WatchService API in Java 7, and how is it used?
WatchService lets an application register a directory and receive notifications when entries are created, deleted, or modified, without having to poll the file system manually. A Path is registered with a WatchService for specific event kinds, and the application then calls watchService.take() in a loop to retrieve WatchKey events as they occur.
11. Explain the Fork/Join framework introduced in Java 7.
The Fork/Join framework (java.util.concurrent) is designed for divide-and-conquer parallelism: a large task is recursively split ("forked") into smaller subtasks that run concurrently, and their results are combined ("joined"). It is powered by ForkJoinPool, which uses a work-stealing algorithm so idle threads can take work from busier threads' queues, improving CPU utilization on multi-core machines.
12. What is the difference between RecursiveTask and RecursiveAction in the Fork/Join framework?
RecursiveTask<V> is used when the subtask computation returns a result (its compute() method returns V), such as summing a range of numbers. RecursiveAction is used when the subtask performs work but returns no result, such as sorting a section of an array in place.
13. How does ForkJoinPool differ from a regular ExecutorService?
ForkJoinPool implements ExecutorService but is optimized for many small, recursively-splitting tasks rather than a fixed set of independent jobs. Its key differentiator is work-stealing: each worker thread has its own deque of tasks, and a thread that runs out of work steals tasks from the tail of another thread's deque, reducing contention and keeping all cores busy.
14. What are binary literals in Java 7?
Java 7 allows integer literals to be expressed in base 2 using the 0b or 0B prefix, which is convenient for representing bit masks and flags directly. For example: int flags = 0b1010_0001;
15. Explain the use of underscores in numeric literals in Java 7.
Underscores can be placed anywhere between digits in a numeric literal to make long numbers more readable; the compiler simply strips them out. For example, int million = 1_000_000; and long creditCardNumber = 1234_5678_9012_3456L; are both valid, but an underscore cannot appear adjacent to a decimal point, at the start/end of a number, or next to an L/f suffix.
16. What is the invokedynamic instruction, and why was it added in Java 7?
invokedynamic is a JVM bytecode instruction added to make it easier and faster to implement dynamically-typed languages (Groovy, JRuby, Jython) on the JVM by deferring method-linkage decisions to runtime via a "bootstrap method" instead of baking them in at compile time. It wasn't used directly by the Java language in version 7, but it later became the foundation for Java 8's lambda expressions.
17. Explain the Objects utility class introduced in Java 7.
java.util.Objects provides static null-safe helper methods such as Objects.equals(a, b), Objects.hashCode(o), Objects.requireNonNull(o), and Objects.toString(o, "default"), reducing repetitive null-checking boilerplate in equals()/hashCode() implementations.
18. What are suppressed exceptions in Java 7's try-with-resources?
If the try block throws an exception and then closing a resource also throws, the exception from the resource's close() call is not lost — it's attached to the primary exception as a "suppressed" exception, retrievable via Throwable.getSuppressed(). This preserves diagnostic information that earlier finally-block patterns would silently discard.
19. What is the purpose of the @SafeVarargs annotation introduced in Java 7?
@SafeVarargs can be applied to a final, static, or private/constructor varargs method to suppress the "unchecked generic array creation" and heap-pollution warnings, telling the compiler (and future readers) that the method does not perform unsafe operations on its varargs parameter array.
20. Explain the concurrency enhancements in Java 7, such as Phaser and TransferQueue.
Phaser is a flexible, reusable synchronization barrier that (unlike CyclicBarrier) supports a dynamically changing number of participating threads across multiple phases. TransferQueue (implemented by LinkedTransferQueue) extends BlockingQueue with a transfer() method that blocks a producer until a consumer actually receives the element, enabling efficient direct hand-off between threads.
21. What is the G1 (Garbage-First) garbage collector introduced in Java 7?
G1 is a server-style, region-based garbage collector introduced experimentally in Java 7 (and made the default much later, in Java 9). It divides the heap into many equal-sized regions and prioritizes collecting the regions containing the most garbage first, aiming for more predictable pause times than the older CMS collector on large heaps.
22. How does catching multiple exception types in one catch block improve code compared to Java 6?
Before Java 7, handling several exception types identically required either a broad catch (Exception e) (losing type specificity) or duplicating the same handler body in separate catch blocks. Multi-catch (catch (IOException | SQLException e)) lets you keep precise exception types while writing the handling logic exactly once, reducing duplication and bytecode size.
23. What improvements did Java 7 NIO.2 bring to copying and moving files?
Files.copy() and Files.move() replace manual stream-based copy loops with single method calls, support CopyOption flags like REPLACE_EXISTING, COPY_ATTRIBUTES, and ATOMIC_MOVE, and surface accurate, specific exceptions (e.g., NoSuchFileException, FileAlreadyExistsException) instead of a generic boolean success/failure result.
24. What are the key differences between Java 6 and Java 7?
Java 7 added language-level syntactic sugar (try-with-resources, multi-catch, diamond operator, string switch, literal improvements), an entirely new file I/O API (NIO.2), the Fork/Join parallel-computation framework, JVM-level support for dynamic languages via invokedynamic, and an experimental G1 collector — none of which existed in Java 6, whose feature set was comparatively modest and heavily focused on JVM and library stability.
25. What are the limitations of Java 7 compared to later versions like Java 8?
Java 7 has no lambda expressions, no functional interfaces, no Stream API, and no built-in Optional type, so collection processing still relies on verbose loops and anonymous inner classes. It also predates the new Date and Time API (java.time), default/static interface methods, and the Metaspace replacement for PermGen — all of which arrived in Java 8 and made code both more concise and safer to maintain.
Java 11 Interview Questions
1. What are the key features introduced in Java 11?
Key features in Java 11 include:
- New HttpClient API (standardized from the Java 9/10 incubator)
- Local-variable syntax (var) for lambda parameters
- New String methods (isBlank(), lines(), strip(), repeat())
- Files.readString()/writeString() and Files.mismatch()
- Nest-Based Access Control
- Epsilon (no-op) Garbage Collector
- ZGC as an experimental low-latency collector
- Launch single-file source-code programs directly with java
- Removal of Java EE/CORBA modules and the deprecated Applet API
A quick illustration combining several of these in one file:
var greeting = " Hello, Java 11 ";
if (!greeting.isBlank()) {
System.out.println(greeting.strip().repeat(2));
}
2. Explain the use of `var` keyword introduced in Java 10 and how it is used in Java 11.
`var` triggers local variable type inference: the compiler determines the concrete type from the initializer expression, so you don't write it explicitly. Java 11 extended this to formal parameters of lambda expressions, which lets you attach annotations (like @Nonnull) to an inferred lambda parameter, something a bare implicit parameter can't do.
var numbers = List.of(1, 2, 3, 4);
numbers.forEach((@Nonnull var n) -> System.out.println(n * n));
3. What is the HttpClient API introduced in Java 11?
The HttpClient API (java.net.http) is a modern client for HTTP requests, supporting HTTP/1.1 and HTTP/2, synchronous and asynchronous calls, and WebSocket connections.
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com"))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
4. How does the new HttpClient API compare to the previous HttpURLConnection?
`HttpURLConnection` is synchronous-only, low-level, and notoriously awkward to configure correctly (streams, redirects, timeouts). `HttpClient` provides a fluent builder API, native HTTP/2 and WebSocket support, and a non-blocking asynchronous mode via sendAsync():
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
5. Explain the use of the `isBlank()` method in Java 11.
`isBlank()` returns `true` if the string is empty or contains only whitespace code points, which is more precise than checking string.trim().isEmpty():
System.out.println(" ".isBlank()); // true
System.out.println("abc".isBlank()); // false
6. What is the `repeat()` method introduced in Java 11?
`repeat(n)` returns a new string consisting of the original string concatenated `n` times:
String result = "ab".repeat(3);
System.out.println(result); // "ababab"
7. How do you use the `lines()` method on a string in Java 11?
`lines()` splits a string on line terminators and returns a `Stream<String>`, avoiding manual `split("\\n")` calls and letting you chain stream operations directly:
String text = "line1\nline2\nline3";
long nonEmpty = text.lines().filter(l -> !l.isBlank()).count();
System.out.println(nonEmpty); // 3
8. What is the `strip()` method in Java 11, and how is it different from `trim()`?
`strip()` removes leading and trailing whitespace using Unicode's definition of whitespace, while the older `trim()` only strips characters with code points `<= U+0020`. This matters for Unicode whitespace like ` ` (EN QUAD), which `trim()` leaves behind:
String s = " Hello ";
System.out.println(s.trim().length()); // whitespace not fully removed
System.out.println(s.strip().length()); // "Hello".length() == 5
9. Explain the new `files.mismatch()` method introduced in Java 11.
`Files.mismatch(path1, path2)` compares two files byte-by-byte and returns the index of the first differing byte, or `-1L` if the files are identical — far more efficient than reading both files fully into memory yourself:
long mismatchIndex = Files.mismatch(Path.of("a.txt"), Path.of("b.txt"));
System.out.println(mismatchIndex == -1L ? "Identical" : "Differ at byte " + mismatchIndex);
10. What are the new options available in `javac` in Java 11?
Java 11's launcher and compiler tooling added support for compiling and running a single-file source program in one step, plus flags for enabling preview language features:
java --enable-preview --source 11 HelloWorld.java
java HelloWorld.java
11. Explain the Nest-Based Access Control in Java 11.
Before Java 11, an outer class and its nested (inner) classes accessing each other's private members required the compiler to generate synthetic bridge methods, since the JVM had no concept of "these classes belong together." Nest-Based Access Control introduces `NestHost`/`NestMembers` class-file attributes so nested classes can access each other's private members directly at the JVM level:
class Outer {
private int secret = 42;
class Inner {
void reveal() {
System.out.println(secret); // direct private access, no synthetic bridge method
}
}
}
12. What is the significance of the `var` keyword in local variables in Java 11?
Using `var` for local variables removes redundant type declarations, especially for verbose generic types, while keeping the variable statically and strongly typed (it's still resolved at compile time, not dynamically typed):
var scores = new HashMap<String, List<Integer>>();
scores.put("alice", List.of(90, 95));
13. What are the key differences between Java 8 and Java 11?
Key differences include:
- Java 11 adds `var`, the new `HttpClient`, additional `String`/`Optional`/`Files` methods, and single-file source execution — none of which existed in Java 8.
- Java 11 introduces new garbage collectors (Epsilon, experimental ZGC) beyond Java 8's Parallel/CMS/G1 options.
- Java 11 is modular (built on the Java 9 module system) and removes Java EE modules, CORBA, and the Applet API that Java 8 still shipped.
- Java 11 is an LTS release, unlike the short-lived Java 9 and 10 feature releases that sit between them.
14. What is the new Epsilon Garbage Collector introduced in Java 11?
Epsilon is a "no-op" garbage collector: it allocates memory but never reclaims it. It exists for performance testing, extremely short-lived processes, and measuring an application's true allocation pressure without GC noise. Enable it with:
java -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC MyApp
15. How does the Epsilon Garbage Collector work?
Epsilon simply hands out memory from the heap linearly and never runs a collection cycle. Once the heap is exhausted it throws an `OutOfMemoryError` — it is only appropriate for short-lived jobs, tightly bounded memory tests, or workloads whose lifetime is guaranteed to fit within the allocated heap.
16. Explain the use of `optional.isEmpty()` method in Java 11.
`isEmpty()` is the logical complement of `isPresent()` introduced in Java 8, letting you avoid an awkward `!optional.isPresent()`:
Optional<String> opt = Optional.empty();
if (opt.isEmpty()) {
System.out.println("No value present");
}
17. What is the significance of the ZGC (Z Garbage Collector) introduced in Java 11?
ZGC is a scalable, low-latency collector (shipped experimentally in Java 11, production-ready since Java 15) designed to keep pause times under a millisecond regardless of heap size, by doing almost all of its work concurrently with the running application:
java -XX:+UnlockExperimentalVMOptions -XX:+UseZGC MyApp
18. Explain the Flight Recorder feature introduced in Java 11.
Java Flight Recorder (JFR), previously a commercial Oracle JDK feature, was open-sourced and bundled into OpenJDK starting with Java 11. It's a low-overhead profiling and event-collection engine built into the JVM, letting you capture CPU, allocation, and lock-contention data from a running production application:
java -XX:StartFlightRecording=filename=recording.jfr,duration=60s MyApp
19. What is the launch single-file source-code programs feature in Java 11?
Java 11 lets you run a `.java` file directly with the `java` launcher — it compiles the source in memory and executes it in one step, without producing a `.class` file on disk, which is handy for quick scripts and demos:
java HelloWorld.java
20. How does Java 11 support running source files directly without compilation?
The `java` launcher detects that its argument is a `.java` source file (rather than a class name), compiles it in memory using the platform compiler, and immediately runs the resulting class — combined with a Unix shebang line, this even lets a Java file be made directly executable:
///usr/bin/env java --source 11
public class Script {
public static void main(String[] args) {
System.out.println("Ran without a separate compile step");
}
}
21. What is the `String.lines()` method in Java 11, and how is it used?
It returns a stream of the string's lines split on line terminators (`\n`, `\r`, or `\r\n`), which is useful for processing multi-line text without manual splitting:
String csv = "id,name\n1,Alice\n2,Bob";
csv.lines().skip(1).forEach(row -> System.out.println("Row: " + row));
22. What is the difference between `stripLeading()` and `stripTrailing()` in Java 11?
`stripLeading()` removes only whitespace from the start of the string, while `stripTrailing()` removes only whitespace from the end — both use the same Unicode whitespace definition as `strip()`:
String s = " padded ";
System.out.println("[" + s.stripLeading() + "]"); // "[padded ]"
System.out.println("[" + s.stripTrailing() + "]"); // "[ padded]"
23. How do you perform file I/O operations using new methods in Java 11?
`Files.readString()` and `Files.writeString()` read/write an entire file's contents as a `String` in one call, replacing several lines of stream boilerplate:
String content = Files.readString(Path.of("notes.txt"));
Files.writeString(Path.of("copy.txt"), content, StandardOpenOption.CREATE);
24. What are the new methods added to the Optional class in Java 11?
Java 9 (not 11) actually added `Optional.or()`, `ifPresentOrElse()`, and `stream()`; Java 11 adds `isEmpty()`. Used together:
Optional<String> opt = Optional.empty();
opt.ifPresentOrElse(
v -> System.out.println("Got: " + v),
() -> System.out.println("Nothing present")
);
long count = opt.or(() -> Optional.of("fallback")).stream().count();
25. Explain the concept of Lambda Parameter Type Inference in Java 11.
This refers to using `var` for lambda parameters (see Q2) so the compiler infers each parameter's type just as it would for a local variable, while still allowing you to attach annotations to the parameter:
BiFunction<Integer, Integer, Integer> add = (var a, var b) -> a + b;
26. What is the purpose of the new Handoff method in Java 11's CompletableFuture?
There is no `handoff` method on `CompletableFuture` in any Java version — this is not a real API. What Java 11 developers actually use to "hand off" a continuation to a specific thread pool is the `*Async` overloads that accept an `Executor`, available since `CompletableFuture` was introduced in Java 8:
ExecutorService pool = Executors.newFixedThreadPool(4);
CompletableFuture.supplyAsync(() -> fetchData())
.thenApplyAsync(data -> process(data), pool)
.thenAccept(System.out::println);
27. How does the `Stream.ofNullable()` method introduced in Java 9 enhance stream processing in Java 11?
`Stream.ofNullable(value)` produces a single-element stream if `value` is non-null, or an empty stream if it's null — useful for flattening a possibly-null value into a larger stream pipeline without an explicit null check:
String maybeNull = lookup("key");
long total = Stream.ofNullable(maybeNull).mapToInt(String::length).sum();
28. What are the new changes introduced in the `java.util.regex` package in Java 11?
Java 11 improved Unicode handling and performance in `Pattern`/`Matcher`, and `Matcher.replaceAll()`/`replaceFirst()` gained overloads that accept a `Function<MatchResult, String>`, avoiding manual `StringBuffer` appending:
String result = Pattern.compile("[0-9]+")
.matcher("id 42 and 7")
.replaceAll(m -> "#" + m.group());
System.out.println(result); // "id #42 and #7"
29. Explain the concept of Pattern Matching for `instanceof` introduced in Java 11.
This feature was not actually introduced in Java 11 — it was previewed in Java 14 (JEP 305) and finalized as a standard feature in Java 16 (JEP 394). Once available, it lets you combine the `instanceof` check and the cast into a single expression, avoiding a separate explicit cast:
Object obj = "hello";
if (obj instanceof String s) {
System.out.println(s.toUpperCase()); // 's' is already a String here
}
Java 17 Interview Questions
1. What are the key features introduced in Java 17?
Key features in Java 17 include:
- Sealed Classes, finalized (JEP 409)
- Pattern Matching for `switch` (Preview, JEP 406)
- Strong Encapsulation of JDK internals by default (JEP 403)
- Enhanced Pseudo-Random Number Generators (JEP 356)
- New macOS Rendering Pipeline using Metal (JEP 382)
- Foreign Function & Memory API (Incubator/Preview, JEP 412)
- Restore Always-Strict Floating-Point Semantics (JEP 306)
- Context-Specific Deserialization Filters (JEP 415)
- Removal of the Solaris and SPARC ports (JEP 381), deprecation of the Applet API
- Text blocks (finalized in Java 15) and Records (finalized in Java 16) continue as standard, non-preview features
2. Explain the concept of Sealed Classes in Java 17.
Sealed Classes restrict which other classes or interfaces may extend or implement them. A class is declared `sealed` and lists its permitted direct subclasses with `permits`, giving the author of a type hierarchy explicit control over its shape rather than leaving it open to any subclass anywhere.
public sealed interface Shape permits Circle, Rectangle {}
3. How do you use Sealed Classes in Java 17?
To use Sealed Classes:
public sealed class Shape permits Circle, Rectangle, Triangle {}
public final class Circle extends Shape {}
public final class Rectangle extends Shape {}
public non-sealed class Triangle extends Shape {}
Each permitted subclass must itself be declared `final`, `sealed`, or `non-sealed`, so the hierarchy's openness is explicit at every level.
4. What are the benefits of using Sealed Classes in Java 17?
Sealed Classes give you better control over the class hierarchy, improved code safety and maintainability, and — combined with pattern matching for `switch` — the compiler can perform exhaustiveness checking, catching a missing case at compile time instead of at runtime:
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
// no default needed: compiler knows Circle/Rectangle are the only subtypes
};
}
5. Explain the concept of Pattern Matching for switch introduced in Java 17.
Pattern Matching for `switch` (preview in Java 17 via JEP 406) lets `switch` match against type patterns and the `null` label directly, instead of only exact constant values:
static String describe(Object obj) {
return switch (obj) {
case Integer i -> "int: " + i;
case String s -> "string: " + s;
case null -> "was null";
default -> "unknown";
};
}
6. How does Pattern Matching for switch improve code readability in Java 17?
It replaces a chain of `instanceof` checks and explicit casts with a single expression. Compare the old style to the new one:
// Before
if (obj instanceof Integer) {
Integer i = (Integer) obj;
System.out.println("int: " + i);
} else if (obj instanceof String) {
String s = (String) obj;
System.out.println("string: " + s);
}
// With pattern matching for switch
System.out.println(describe(obj));
7. What is the purpose of the new JEP 356: Enhanced Pseudo-Random Number Generators in Java 17?
JEP 356 introduces the `RandomGenerator` interface hierarchy so all pseudo-random algorithms (legacy and new) share a common API, and adds several new, higher-quality algorithms alongside the classic `Random`:
RandomGenerator rng = RandomGeneratorFactory.of("L64X128MixRandom").create();
int value = rng.nextInt(100);
8. How do the new random number generator interfaces work in Java 17?
`RandomGeneratorFactory` looks algorithms up by name and creates instances implementing `RandomGenerator` (with sub-interfaces like `SplittableGenerator` and `JumpableGenerator` for parallel/streaming use cases), so code depending on the interface can swap algorithms without changing call sites:
RandomGeneratorFactory.all()
.map(RandomGeneratorFactory::name)
.forEach(System.out::println); // lists every available algorithm
9. Explain the new JEP 382: New macOS Rendering Pipeline in Java 17.
JEP 382 replaces the deprecated OpenGL-based Java 2D rendering pipeline on macOS with one built on Apple's Metal framework, improving graphics performance and compatibility with newer macOS releases. This is an internal JVM/AWT implementation change with no corresponding Java-level API or code snippet — applications don't call into it directly.
10. What is the JEP 409: Sealed Classes in Java 17, and how is it implemented?
JEP 409 is the finalization of Sealed Classes as a standard language feature. It's implemented via the `sealed` modifier plus a `permits` clause naming the allowed direct subtypes, which the compiler validates and records in the class file:
public sealed interface Vehicle permits Car, Truck, Motorcycle {}
public record Car(String model) implements Vehicle {}
public record Truck(double payloadTons) implements Vehicle {}
public record Motorcycle(boolean hasSidecar) implements Vehicle {}
11. How do JEP 356 and JEP 409 enhance the security and performance of Java applications?
JEP 356 offers faster, higher-quality, and more consistent random number generation across algorithms (relevant to simulations and, with care, cryptographic-adjacent code), while JEP 409 improves security and correctness by letting API authors close off a type hierarchy to a known, auditable set of subclasses instead of leaving it open to arbitrary extension.
12. What are the new enhancements to ZGC (Z Garbage Collector) in Java 17?
Java 17 continues maturing ZGC (made production-ready in Java 15) with better handling of concurrent thread-stack processing and further latency reductions, keeping pause times consistently under a millisecond:
java -XX:+UseZGC -Xmx8g MyApp
13. Explain the new JEP 403: Strong Encapsulation by Default in Java 17.
JEP 403 makes all internal (non-exported) elements of JDK modules strongly encapsulated by default — `--illegal-access` (which previously allowed reflective access with a warning) is removed, so reflective access to internal APIs now fails unless the module explicitly opens or exports the package:
module com.example.app {
exports com.example.app.api; // only this package is accessible to other modules
}
14. How does strong encapsulation impact modularity in Java 17?
It forces libraries and applications to depend only on explicitly exported, supported APIs rather than reaching into JDK internals via reflection — a common source of fragile upgrades in older codebases — improving long-term maintainability at the cost of requiring `--add-opens`/`--add-exports` flags for legacy code that still needs internal access.
15. What are the improvements in JEP 356: Enhanced Pseudo-Random Number Generators?
Beyond the new interface hierarchy (Q7/Q8), JEP 356 adds convenient stream-based generation methods for producing large sequences of random values without manual loops:
RandomGenerator rng = RandomGeneratorFactory.of("Xoroshiro128PlusPlus").create();
rng.ints(5, 0, 100).forEach(System.out::println); // 5 random ints in [0, 100)
16. How does the new JEP 356 impact cryptography in Java 17?
JEP 356's generators are pluggable and higher-quality than the legacy `Random`, but they are still meant for statistical/simulation use, not security — `SecureRandom` remains the correct choice for cryptographic key or nonce generation. JEP 356's main cryptography-adjacent benefit is giving library authors a consistent interface to depend on rather than hardcoding `java.util.Random`.
17. What is the JEP 415: Context-Specific Deserialization Filters in Java 17?
JEP 415 lets you attach a deserialization filter to an individual `ObjectInputStream`, selectively allowing or rejecting classes during deserialization based on the specific call site, rather than only a single global, process-wide filter:
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter("com.example.*;!*");
ObjectInputStream ois = new ObjectInputStream(inputStream);
ois.setObjectInputFilter(filter);
Object obj = ois.readObject(); // only com.example.* classes are allowed
18. How do context-specific deserialization filters enhance security in Java 17?
They let different parts of an application apply the narrowest possible allow-list of deserializable classes for that specific stream, closing off a major class of deserialization-gadget-chain vulnerabilities without requiring one overly permissive global filter shared by unrelated code paths.
19. What are the new Foreign Function & Memory API preview features in Java 17?
JEP 412 (incubator in 17) introduces `MemorySegment`, `MemoryAddress`, and `ResourceScope` for safely allocating and manipulating off-heap (native) memory from Java, as a safer, more efficient replacement for `sun.misc.Unsafe` and JNI-based native buffers:
try (ResourceScope scope = ResourceScope.newConfinedScope()) {
MemorySegment segment = MemorySegment.allocateNative(4L, scope);
MemoryAccess.setInt(segment, 42);
System.out.println(MemoryAccess.getInt(segment));
}
20. How does the Foreign Function & Memory API enhance interoperability in Java 17?
Alongside off-heap memory access, the API's `CLinker`/linker support lets Java code call native (C) library functions directly, without hand-written JNI glue code, reducing both boilerplate and the risk of memory-safety bugs when integrating with native libraries.
21. Explain the improvements in JEP 381: Remove the Solaris and SPARC Ports in Java 17.
JEP 381 removes all source code and build support for the Solaris OS and SPARC CPU architecture ports, which had already been deprecated in Java 14 (JEP 362). This is a codebase and build-system change with no corresponding application-level API or code sample.
22. What is the impact of removing the Solaris and SPARC ports in Java 17?
It simplifies the OpenJDK codebase and build/test matrix, letting the project focus engineering effort on Linux, Windows, and macOS across x86/ARM — platforms that make up the overwhelming majority of real-world Java deployments.
23. What is JEP 412: Foreign Function & Memory API (Incubator) in Java 17?
JEP 412 is the incubator-module vehicle that ships the Foreign Function & Memory API (see Q19/Q20) for real-world testing and feedback before it becomes a permanent, non-incubating API (which happened in later releases, finalized in Java 22). Using it in 17 requires the incubator module explicitly:
javac --add-modules jdk.incubator.foreign Main.java
java --add-modules jdk.incubator.foreign Main
24. How does JEP 412 support better performance in native code integration?
By allowing direct, JIT-friendly access to native memory and native function calls without going through JNI's costly transition overhead and hand-written glue code, JEP 412 reduces both the performance cost and the memory-safety risk of integrating with native libraries.
25. What is the JEP 306: Restore Always-Strict Floating-Point Semantics in Java 17?
JEP 306 makes all floating-point operations `strictfp` by default again — Java originally required strict IEEE 754 semantics everywhere, relaxed that in Java 1.2 to accommodate certain hardware, and JEP 306 restores the original strict, always-consistent behavior now that essentially all hardware supports it natively:
// The 'strictfp' keyword is now redundant everywhere — strict semantics are the default
public strictfp class Calc { /* ... */ }
26. Explain the significance of always-strict floating-point semantics in Java 17.
Guaranteed strict semantics mean a floating-point computation produces bit-for-bit identical results on every platform and JVM implementation, which matters for reproducible scientific computing, financial calculations, and deterministic testing across environments.
27. What is the new JEP 356 API, and how does it differ from the older random number generator APIs?
Compare the legacy approach to the JEP 356 approach:
// Older API: tied to one specific implementation
Random legacy = new Random();
int a = legacy.nextInt(100);
// JEP 356: pick any algorithm behind a common interface
RandomGenerator modern = RandomGeneratorFactory.of("L128X256MixRandom").create();
int b = modern.nextInt(100);
The new API is algorithm-agnostic, so code can switch generators (for better statistical quality or performance) by changing only the factory name string.
28. How do you use the enhanced switch statement in Java 17?
Beyond pattern matching, Java 17 continues to support the arrow-form `switch` expression (finalized in Java 14) which avoids fall-through and can directly produce a value with `yield`:
int day = 3;
String name = switch (day) {
case 1, 7 -> "Weekend";
case 2, 3, 4, 5, 6 -> "Weekday";
default -> {
yield "Unknown";
}
};
29. What are the changes to the `java.util.regex` package in Java 17?
Java 17 itself made no major `java.util.regex` API additions (the notable `Matcher.replaceAll(Function)` improvement landed in Java 9, and `Pattern` continues to receive incremental Unicode and performance updates across releases). Existing regex code is unaffected and continues to work as-is:
Matcher m = Pattern.compile("(\\d+)").matcher("Order #482");
if (m.find()) {
System.out.println(m.group(1)); // "482"
}
30. Explain the improvements in pattern matching introduced in Java 17.
Java 17 carries forward finalized pattern matching for `instanceof` (Java 16) and previews pattern matching for `switch` (JEP 406), letting you combine type tests, casts, and branching into fewer, more expressive constructs:
static String category(Object obj) {
if (obj instanceof Integer i && i > 0) {
return "positive int";
}
return switch (obj) {
case String s -> "string of length " + s.length();
default -> "other";
};
}
31. What is the new JEP 403: Strong Encapsulation? How does it change the module system?
It changes the module system's default posture from "internals reachable via reflection with a warning" to "internals inaccessible unless explicitly opened." Code that needs internal access must now be granted it explicitly at launch:
java --add-opens java.base/java.lang=ALL-UNNAMED MyLegacyApp
32. How does Java 17 handle pattern matching for `instanceof` in switch cases?
The `switch` preview (JEP 406) lets a `case` label be a type pattern rather than only a constant, binding a typed variable directly in the matching branch:
static String render(Object shape) {
return switch (shape) {
case Circle c -> "circle r=" + c.radius();
case Rectangle r -> "rect " + r.width() + "x" + r.height();
default -> "unknown shape";
};
}
33. What are the significant changes in the garbage collection mechanism in Java 17?
Java 17 continues refining both G1 (the default collector) and ZGC (low-latency, still opt-in) with lower overhead and better handling of large heaps and concurrent thread-stack scanning, rather than introducing an entirely new collector — the Epsilon and Shenandoah/ZGC options introduced in Java 11-15 remain the main alternatives to the default G1.
34. Explain the use of `instanceof` pattern matching in Java 17.
Finalized since Java 16, `instanceof` pattern matching combines the type check and the cast into one expression, with the bound variable scoped to where the check is known to be true:
Object obj = "hello world";
if (obj instanceof String s && s.length() > 5) {
System.out.println(s.toUpperCase());
}
35. How do Sealed Classes compare to traditional inheritance models in Java 17?
Traditional (non-sealed) inheritance lets any class in any package extend a public non-final class, so the full set of subtypes is unknowable at compile time. Sealed Classes make that set closed and explicit via `permits`, enabling compile-time exhaustiveness checks in `switch` and clearer API contracts, at the cost of requiring all permitted subclasses to be known and (typically) co-located with the sealed type.
36. What are the new features in text blocks introduced in Java 17?
Text blocks themselves were finalized in Java 15 (JEP 378) and Java 17 introduces no new text-block syntax — they remain available as a standard feature for writing multi-line string literals (JSON, HTML, SQL) without escape-heavy concatenation:
String json = """
{
"name": "Java",
"version": 17
}
""";
37. Explain the enhanced Record class introduced in Java 17.
Records, finalized in Java 16 (JEP 395), are immutable data carriers: declaring a record automatically generates a canonical constructor, private final fields, accessor methods, and `equals()`/`hashCode()`/`toString()`. Java 17 adds no new record syntax but records continue to be a standard feature and combine naturally with sealed interfaces and pattern matching:
public record Point(int x, int y) {
public Point {
if (x < 0 || y < 0) throw new IllegalArgumentException("must be non-negative");
}
}
38. What are the advantages of using the Record class over traditional POJOs?
A record collapses dozens of lines of boilerplate into one declaration line, while guaranteeing immutability (all fields are `final`) and value-based `equals()`/`hashCode()`:
// Traditional POJO: ~25 lines with getters, equals, hashCode, toString, constructor
// Record: equivalent behavior in one line
public record Point(int x, int y) {}
39. How does Java 17 improve the performance of the JVM?
Java 17's JVM performance gains come mainly from continued ZGC/G1 tuning (Q12/Q33), JIT compiler improvements inherited from the ongoing HotSpot work across releases, and macOS-specific rendering gains from JEP 382 (Q9) — it is an accumulation of incremental engine improvements rather than one single new performance feature.
40. What is the significance of JEP 306: Restore Always-Strict Floating-Point Semantics in Java 17?
Beyond cross-platform reproducibility (Q25/Q26), JEP 306's practical significance is that it removes a subtle, long-standing class of "it works on my machine" bugs in numerically-sensitive code (simulations, financial math, scientific computing) caused by the small number of platforms that previously used the relaxed floating-point mode.
41. What are the most critical changes in the Java language syntax in Java 17?
The most consequential syntax-level change finalized by Java 17 is Sealed Classes (`sealed`/`non-sealed`/`permits`), building on Records (Java 16) and text blocks (Java 15); Pattern Matching for `switch` remains in preview. Together they form a cohesive shift toward algebraic-data-type-style modeling in Java:
public sealed interface Shape permits Circle, Square {}
public record Circle(double radius) implements Shape {}
public record Square(double side) implements Shape {}
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square sq -> sq.side() * sq.side();
};
}
Java 21 Interview Questions
1. What are the key features introduced in Java 21?
Java 21 (the current LTS release) bundles several major JEPs:
- Virtual Threads (JEP 444)
- Structured Concurrency (JEP 453, Preview)
- Pattern Matching for switch (JEP 441)
- Record Patterns (JEP 440)
- Sequenced Collections (JEP 431)
- String Templates (JEP 430, Preview)
- Scoped Values (JEP 446, Preview)
- Generational ZGC (JEP 439)
- Unnamed Patterns and Variables (JEP 443, Preview)
- Key Encapsulation Mechanism API (JEP 452)
2. Explain Virtual Threads introduced in Java 21 (JEP 444).
Virtual threads are lightweight threads managed by the JVM rather than the OS. Millions can be created cheaply because they don't map one-to-one onto OS threads; instead, many virtual threads are multiplexed onto a small pool of OS "carrier" threads, and a virtual thread is unmounted from its carrier whenever it blocks on I/O or another blocking operation. This lets simple thread-per-request/thread-per-task code scale to huge numbers of concurrent tasks without needing reactive or asynchronous rewrites. Example:
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
executor.submit(() -> handleRequest());
}
}
3. What is the difference between virtual threads and platform threads?
Platform threads are thin wrappers around OS threads: they are relatively expensive to create (megabytes of stack, kernel scheduling overhead), so applications typically pool a few hundred of them. Virtual threads are JVM-managed, have a small initial footprint that grows as needed, are scheduled by the JVM (not the OS scheduler), and are designed to be created in the millions, one per task, without pooling.
4. Explain Structured Concurrency in Java 21 (JEP 453, Preview).
Structured Concurrency treats a group of related concurrent subtasks launched together as a single unit of work: if the main task is cancelled, or one subtask fails, the others are automatically cancelled too, and errors propagate coherently to the caller instead of leaking into separate, independently-failing threads. It is used via StructuredTaskScope, which ties the lifetime of child tasks to a well-defined lexical scope, making concurrent code easier to reason about, observe, and debug.
5. What is Pattern Matching for switch in Java 21 (JEP 441), and how is it finalized?
Pattern Matching for switch, previewed since Java 17/18/19/20, became a permanent, standard language feature in Java 21. It lets switch statements and expressions match against type patterns, record patterns, and the null label directly, with optional guarded patterns (case Integer i when i > 0), replacing chains of instanceof/cast with a single expressive construct.
6. Explain Record Patterns in Java 21 (JEP 440).
Record Patterns let you deconstruct a record's components directly inside a pattern (in instanceof or switch), binding its fields to local variables in one step instead of calling accessor methods manually. For example:
record Point(int x, int y) {}
if (obj instanceof Point(int x, int y)) {
System.out.println(x + y);
}
7. How do nested record patterns work? Provide an example.
Record patterns can nest, letting you deconstruct records-within-records in a single match. For example:
record Point(int x, int y) {}
record Line(Point start, Point end) {}
static String describe(Object o) {
return switch (o) {
case Line(Point(var x1, var y1), Point(var x2, var y2)) ->
"Line from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ")";
default -> "unknown";
};
}
8. What are Sequenced Collections introduced in Java 21 (JEP 431)?
Sequenced Collections add a common set of interfaces — SequencedCollection, SequencedSet, and SequencedMap — that formalize "collections with a defined encounter order" and provide uniform operations for accessing the first and last elements and iterating in reverse, regardless of the concrete collection type (e.g., ArrayList, LinkedHashSet, LinkedHashMap).
9. What new methods do Sequenced Collections add, and why were they needed?
They add getFirst(), getLast(), addFirst(), addLast(), removeFirst(), removeLast(), and reversed(). Before Java 21, getting the "first" or "last" element of an ordered collection required different, inconsistent idioms per type (e.g., list.get(0) vs. deque.peekFirst() vs. manually iterating a LinkedHashMap), and there was no clean way to obtain a reversed view — these methods unify that behavior across the collection hierarchy.
10. Explain String Templates introduced in Java 21 (JEP 430, Preview).
String Templates let you embed expressions directly inside string literals using a template processor, combining literal text with embedded expressions more safely and readably than concatenation or String.format(). Example using the standard STR processor:
String name = "World";
String greeting = STR."Hello, \{name}!";
Unlike naive concatenation, template processors can also validate and safely escape embedded values, which is useful for building SQL, JSON, or HTML without injection risks.
11. What are Scoped Values in Java 21 (JEP 446, Preview), and how do they differ from ThreadLocal?
ScopedValue lets a value be shared immutably with a method and everything it calls, for the duration of a well-defined dynamic scope, then automatically revert afterward. Unlike ThreadLocal, a scoped value is set once (via ScopedValue.where(...).run(...)) and cannot be mutated afterward, its lifetime is bound to that scope rather than the thread's entire lifetime, and — crucially — it is cheap to inherit across the huge numbers of virtual threads that structured concurrency spawns, avoiding the memory overhead ThreadLocal incurs when copied to child threads.
12. Explain Generational ZGC introduced in Java 21 (JEP 439).
Generational ZGC extends the low-latency Z Garbage Collector with separate generations for young (short-lived) and old (long-lived) objects, following the well-established observation that most objects die young. By collecting the young generation more frequently and cheaply, it reduces overall CPU and memory overhead compared to the original single-generation ZGC, while preserving ZGC's sub-millisecond pause-time guarantees.
13. What is the Key Encapsulation Mechanism API introduced in Java 21 (JEP 452)?
The KEM API (javax.crypto.KEM) provides a standard interface for key encapsulation mechanisms — cryptographic algorithms used to securely establish a shared secret key between two parties, notably including post-quantum-safe schemes — so applications and libraries no longer need to implement bespoke, algorithm-specific integrations.
14. Explain Unnamed Patterns and Variables introduced in Java 21 (JEP 443, Preview).
Unnamed patterns and variables let you use an underscore (_) as a placeholder wherever a variable must be declared syntactically but its value is never actually used — for example, in a record pattern component you don't care about, or a catch block or lambda parameter you must declare but ignore. This makes intent clearer and avoids unused-variable warnings/naming churn:
if (obj instanceof Point(var x, var _)) {
System.out.println("x = " + x);
}
15. What is the purpose of JEP 451: Prepare to Disallow the Dynamic Loading of Agents?
JEP 451 issues a warning when a Java agent is dynamically attached to an already-running JVM (e.g., via the Attach API used by some profilers and monitoring tools) unless the -XX:+EnableDynamicAgentLoading flag is set. It is the first step toward eventually requiring all instrumentation agents to be specified up front at JVM startup, closing off a class of unexpected runtime modification for stronger integrity guarantees.
16. Why is Java 21 significant as an LTS release?
Java 21 is a Long-Term Support release that most enterprises will run in production for years, and it is the first LTS to ship virtual threads, structured concurrency (preview), record patterns, and finalized pattern matching for switch — a substantial jump in both concurrency model and language expressiveness compared to the previous LTS, Java 17.
17. How do virtual threads improve throughput for I/O-bound applications?
In a traditional thread-per-request model backed by platform threads, a thread blocked on I/O (a database call, an HTTP request) ties up a scarce, expensive OS thread and its stack memory, forcing servers to cap concurrency or adopt complex asynchronous/reactive code. Virtual threads that block on I/O are automatically unmounted from their carrier platform thread, freeing that carrier to run other virtual threads; this lets an application handle vastly more concurrent I/O-bound requests using ordinary blocking, synchronous code and far fewer OS threads.
18. What is thread "pinning," and why is it a limitation of virtual threads?
Pinning occurs when a virtual thread cannot be unmounted from its carrier platform thread while blocked — for example, inside a synchronized block or method, or during certain native calls — so the carrier thread is stuck waiting instead of being freed to run other virtual threads. This can reduce the scalability benefit of virtual threads under heavy contention on synchronized code, and is why Java 21 recommends replacing synchronized with java.util.concurrent locks in performance-sensitive, high-concurrency code that uses virtual threads.
19. How does structured concurrency improve error handling and cancellation compared to raw ExecutorService usage?
With a bare ExecutorService, submitted subtasks run independently — if one fails, the caller must manually track and cancel the others, and errors can be missed or leaked as unhandled exceptions on background threads. StructuredTaskScope groups subtasks under one enclosing scope so that a failure (or cancellation) in one subtask automatically cancels the sibling subtasks, and the scope's join()/throwIfFailed() methods surface a single coherent outcome to the caller, preventing thread leaks and orphaned work.
20. How do guarded patterns (`when` clauses) work in switch pattern matching in Java 21?
A guarded pattern adds a boolean condition after a case pattern using the when keyword, so the case only matches if both the pattern matches and the guard evaluates to true — letting you express refined conditions that plain type patterns alone can't:
static String classify(Object obj) {
return switch (obj) {
case Integer i when i > 0 -> "positive integer";
case Integer i when i < 0 -> "negative integer";
case Integer i -> "zero";
default -> "not an integer";
};
}
21. What is the significance of exhaustiveness checking in switch pattern matching over sealed types?
When a switch's selector type is a sealed class/interface, the compiler knows the complete, closed set of permitted subtypes and can verify at compile time that every case pattern has been covered, without requiring a default branch. This turns a whole category of "forgot to handle a new subtype" bugs into compile errors, and combines naturally with sealed classes and record patterns for safe, exhaustive data modeling.
22. What does the reversed() method on a Sequenced Collection return?
reversed() returns a view of the collection with its encounter order reversed — it does not copy the elements. Changes made through the reversed view are reflected in the original collection and vice versa, so it's a cheap way to iterate, search, or process a list, set, or map's entries from last to first.
23. What are the key differences between Java 17 and Java 21?
Java 21 builds on Java 17 by adding virtual threads and structured concurrency for scalable concurrency, finalizing pattern matching for switch and adding record patterns for more expressive data handling, introducing Sequenced Collections for consistent ordered-collection APIs, previewing string templates and scoped values, and upgrading ZGC to a generational collector — a much larger leap in language and concurrency capability than the gap between Java 11 and Java 17.
24. How would you migrate a thread-per-request server to use virtual threads in Java 21?
In most cases you simply swap the underlying ExecutorService for Executors.newVirtualThreadPerTaskExecutor() (or configure your framework, e.g., Tomcat/Spring Boot, to use a virtual-thread executor) and keep the existing blocking, synchronous request-handling code as-is. You should then audit hot paths for heavy use of synchronized blocks or thread pools sized to a small fixed number (which assume expensive platform threads), and remove artificial concurrency limits that were only there to avoid exhausting platform threads.
25. What should you consider before adopting Java 21 in production?
Check that all critical dependencies and frameworks officially support Java 21, avoid relying on preview features (structured concurrency, string templates, scoped values, unnamed patterns) in production code since their APIs can still change before finalization, review code for synchronized-block pinning if you plan to lean heavily on virtual threads, and validate garbage collector behavior (especially if switching to generational ZGC) under your actual production workload before rolling it out broadly.

Add your comments for more improvement!
ReplyDelete