Java Progressive Master Question Bank
75 progressive Java interview questions complete with technical explanations, key takeaways, diagrams, code examples, and interactive knowledge check quizzes.
Q61: What is Local Variable Type Inference (var in Java 10) and its restrictions?
var allows the compiler to infer local variable types from initializer expressions at compile time. Static typing is preserved.
- Restrictions:
- Allowed ONLY for local variables with initializers.
- CANNOT be used for class fields, method parameter signatures, or return types.
- CANNOT be initialized to
nullor array initializers without explicit types (var x = nullis illegal).
// Valid
var list = new ArrayList<String>(); // Inferred as ArrayList<String>
var stream = list.stream();
// Invalid / Compile Error
var x; // Error: Needs initializer
var y = null; // Error: Cannot infer type from nullvaris strictly local type inference at compile time.- Illegal on class instance fields, method parameters, or null initializations.
Can var be used to declare instance variables (fields) inside a class definition?
Q62: What is the modern HttpClient API introduced in Java 11?
Java 11 replaced legacy HttpURLConnection with java.net.http.HttpClient.
- Features: Supports HTTP/1.1 and HTTP/2, WebSockets, non-blocking asynchronous requests via
CompletableFuture, reactive stream body handlers (BodyHandlers.ofString()).
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/data"))
.GET()
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);- Native support for HTTP/2, WebSockets, and non-blocking async requests.
Which protocol is supported natively by the Java 11 HttpClient API out of the box?
Q63: What are Java Records (Java 16+) and how do they eliminate boilerplate?
record is an immutable data carrier class. The compiler automatically generates final fields, canonical constructor, getters (field()), equals(), hashCode(), and toString().
- Restrictions: Records cannot extend other classes (they implicitly extend
java.lang.Record). Fields are strictlyfinal.
public record User(long id, String name, String email) {
// Compact constructor for validation
public User {
Objects.requireNonNull(name, "Name cannot be null");
}
}- Immutable data carrier class.
- Generates fields, getters,
equals,hashCode, andtoStringautomatically.
Can a Java Record extend a class using the extends keyword?
Q64: What are Sealed Classes and Interfaces (Java 17+)?
Sealed Classes (sealed) restrict which subclasses are permitted to extend or implement them using the permits clause.
- Subclass Rules: Permitted subclasses MUST explicitly declare one of three modifiers:
final: Cannot be extended further.sealed: Can be extended by a restricted list of subclasses.non-sealed: Opens hierarchy to unrestricted inheritance.
public sealed class Shape permits Circle, Square {}
public final class Circle extends Shape {} // Final
public non-sealed class Square extends Shape {} // Opened hierarchy- Restricts inheritance hierarchies using
permits. - Subclasses must be
final,sealed, ornon-sealed.
Which keyword modifier must be declared on a permitted subclass to reopen it for unrestricted inheritance?
Q65: How does Pattern Matching for switch work (Java 21+)?
Pattern Matching for switch allows inspecting object types directly within switch expressions, binding variables automatically, using guard clauses (when), and handling null cases cleanly.
public static String formatValue(Object obj) {
return switch (obj) {
case Integer i -> String.format("Int: %d", i);
case String s when s.length() > 5 -> "Long String: " + s.toUpperCase();
case String s -> "Short String: " + s;
case null -> "Null Value";
default -> obj.toString();
};
}- Type pattern matching inside switch expressions.
- Supports guard clauses using
whencondition filters.
Which keyword introduces additional conditional filters (guard clauses) inside pattern matching switch cases?
Q66: What are Virtual Threads (Project Loom - Java 21) and how do they differ from Platform Threads?
- Platform Threads: $1 o 1$ mapping to OS native threads. Heavy memory stack footprint (~1MB), expensive context switching. Limited to thousands of threads.
- Virtual Threads: Lightweight JVM-managed threads ($M o N$ mapping onto a small pool of Platform Carrier Threads). Extremely low memory footprint (~few KB). Allows scaling applications to millions of concurrent threads.
- Virtual Threads enable millions of concurrent threads with minimal memory overhead.
- Mounted dynamically onto OS Carrier Threads by the JVM during execution.
What primary problem do Virtual Threads solve in high-throughput enterprise applications?
Q67: What is Thread Pinning in Virtual Threads and what causes it?
Virtual Threads unmount from Carrier Threads when performing blocking I/O. Thread Pinning occurs when a Virtual Thread CANNOT unmount from its OS Carrier Thread during a blocking call, tying up OS thread capacity.
- Causes: Executing blocking operations inside
synchronizedblocks or methods, or calling native JNI methods. - Fix: Replace
synchronizedblocks withReentrantLock.
- Pinning occurs when a Virtual Thread cannot unmount from its OS Carrier Thread.
- Avoid
synchronizedinside high-concurrency Virtual Thread paths; useReentrantLock.
How can developers prevent Thread Pinning inside Virtual Thread execution paths?
Q68: What are Sequenced Collections introduced in Java 21?
Java 21 introduced unified interfaces for collections with defined encounter order: SequencedCollection, SequencedSet, SequencedMap.
- Standardized Methods:
addFirst(),addLast(),getFirst(),getLast(),removeFirst(),removeLast(), andreversed()(returns a reverse-ordered view).
List<String> list = new ArrayList<>(List.of("B", "C"));
list.addFirst("A"); // [A, B, C]
list.addLast("D"); // [A, B, C, D]
String first = list.getFirst(); // "A"
List<String> reversed = list.reversed(); // [D, C, B, A]- Unified interfaces for collections with defined element ordering.
- Provides standardized methods:
getFirst(),getLast(),reversed().
Which method in SequencedCollection returns a reverse-ordered view of the underlying collection?
Q69: What is Structured Concurrency (Java 21 / Preview) and how does StructuredTaskScope work?
Structured Concurrency treats concurrent tasks running in separate threads as a single unit of work. Using StructuredTaskScope, child threads spawned to process sub-tasks share the lifespan and execution scope of their parent task, ensuring clean cancellation, error propagation, and observability.
- Treats concurrent sub-tasks as a unified structured scope.
- Ensures child thread failures automatically cancel sibling tasks.
What happens in StructuredTaskScope.ShutdownOnFailure when one child sub-task throws an exception?
Q70: What are Scoped Values (Java 21 / Preview) and how do they improve upon ThreadLocal?
ScopedValue provides immutable, thread-confined value sharing suitable for thousands/millions of Virtual Threads.
- Improvements over
ThreadLocal:- Immutable: Cannot be modified once bound.
- Bounded Lifetime: Automatically unbound when scope exits (eliminates thread pool memory leaks).
- Efficient Inheritance: Child virtual threads share scope context efficiently.
- Immutable, bounded-lifetime alternative to
ThreadLocal. - Prevents memory leaks across thread executions automatically.
What is the key lifecycle safety advantage of ScopedValue over ThreadLocal?