HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
75 Topics
Chapter•390 Minutes

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 null or array initializers without explicit types (var x = null is illegal).
Valid vs Invalid var Declarations
// 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 null
💡 var requires explicit local initializers to determine variable types at compile time.
Key Takeaways
  • var is strictly local type inference at compile time.
  • Illegal on class instance fields, method parameters, or null initializations.
Knowledge Check

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()).
Java 11 HttpClient Async Request
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);
💡 HttpClient supports non-blocking asynchronous HTTP requests using CompletableFuture.
Key Takeaways
  • Native support for HTTP/2, WebSockets, and non-blocking async requests.
Knowledge Check

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 strictly final.
Java Record Declaration
public record User(long id, String name, String email) {
    // Compact constructor for validation
    public User {
        Objects.requireNonNull(name, "Name cannot be null");
    }
}
💡 Compact constructor allows adding validation while generating immutable fields automatically.
Key Takeaways
  • Immutable data carrier class.
  • Generates fields, getters, equals, hashCode, and toString automatically.
Knowledge Check

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:
    1. final: Cannot be extended further.
    2. sealed: Can be extended by a restricted list of subclasses.
    3. non-sealed: Opens hierarchy to unrestricted inheritance.
Sealed Class Hierarchy
public sealed class Shape permits Circle, Square {}

public final class Circle extends Shape {} // Final
public non-sealed class Square extends Shape {} // Opened hierarchy
💡 Shape limits direct inheritance strictly to Circle and Square.
Key Takeaways
  • Restricts inheritance hierarchies using permits.
  • Subclasses must be final, sealed, or non-sealed.
Knowledge Check

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.

Pattern Matching for Switch with Guard Clause
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();
    };
}
💡 Direct type matching with automatic variable casting and guard clause conditions.
Key Takeaways
  • Type pattern matching inside switch expressions.
  • Supports guard clauses using when condition filters.
Knowledge Check

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 vs Platform OS Threads Architecture
Key Takeaways
  • Virtual Threads enable millions of concurrent threads with minimal memory overhead.
  • Mounted dynamically onto OS Carrier Threads by the JVM during execution.
Knowledge Check

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 synchronized blocks or methods, or calling native JNI methods.
  • Fix: Replace synchronized blocks with ReentrantLock.
Key Takeaways
  • Pinning occurs when a Virtual Thread cannot unmount from its OS Carrier Thread.
  • Avoid synchronized inside high-concurrency Virtual Thread paths; use ReentrantLock.
Knowledge Check

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(), and reversed() (returns a reverse-ordered view).
SequencedCollection Operations
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]
💡 SequencedCollection standardizes first/last access and reverse-view operations.
Key Takeaways
  • Unified interfaces for collections with defined element ordering.
  • Provides standardized methods: getFirst(), getLast(), reversed().
Knowledge Check

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.

Key Takeaways
  • Treats concurrent sub-tasks as a unified structured scope.
  • Ensures child thread failures automatically cancel sibling tasks.
Knowledge Check

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:
    1. Immutable: Cannot be modified once bound.
    2. Bounded Lifetime: Automatically unbound when scope exits (eliminates thread pool memory leaks).
    3. Efficient Inheritance: Child virtual threads share scope context efficiently.
Key Takeaways
  • Immutable, bounded-lifetime alternative to ThreadLocal.
  • Prevents memory leaks across thread executions automatically.
Knowledge Check

What is the key lifecycle safety advantage of ScopedValue over ThreadLocal?