Java 17 to 21 Interview Questions: Records, Pattern Matching, Virtual Threads

Most Java interview question banks are frozen in 2016 — they never mention records, pattern matching, or virtual threads. Interviewers in 2026 notice. These are the Java 17–21 questions actually being asked now, each with the answer that earns the point and the follow-up it triggers.

1. What is a record, and when would you use one instead of a class?

A record is a compact, immutable data carrier. The compiler generates the constructor, accessors, equals, hashCode, and toString:

record Order(String orderId, BigDecimal amount) {}

// canonical constructor can still validate:
record Order(String orderId, BigDecimal amount) {
    Order {
        if (amount.signum() < 0) throw new IllegalArgumentException("negative amount");
    }
}

Answer: use a record when the class is transparent immutable data — DTOs, API responses, map keys, tuple-like returns. Use a regular class when you need mutable state, inheritance, or rich behavior. Follow-up bait: "Can a record extend another class?" — No; records implicitly extend java.lang.Record and can't extend anything else (but they can implement interfaces).

2. What are sealed classes?

sealed interface Payment permits CardPayment, UpiPayment, CashPayment {}
final class CardPayment implements Payment { /* ... */ }

Answer: sealed types declare exactly which classes may extend/implement them. The payoff: the compiler knows the full set, so a switch over a sealed type needs no default — and adding a new permitted type breaks compilation at every switch, forcing you to handle it. That's exhaustiveness checking, and it's the interviewer's favorite follow-up.

3. Explain pattern matching for instanceof and switch

// old way
if (obj instanceof String) {
    String s = (String) obj;   // redundant cast
    ...
}

// pattern matching: binds s in one step
if (obj instanceof String s && !s.isBlank()) {
    System.out.println(s.toUpperCase());
}

// pattern matching in switch — the real power move
static String describe(Object o) {
    return switch (o) {
        case String s  -> "string of length " + s.length();
        case Integer i -> "int: " + i;
        case null      -> "null!";
        default        -> "something else";
    };
}

Answer: pattern matching collapses type-test + cast + branch into one construct. Note that switch now handles null explicitly instead of throwing NPE — interviewers love asking "what happens on null in a pattern switch?"

4. What changed with switch expressions?

Answer: switch became an expression (returns a value) with arrow syntax, no fall-through, and it must be exhaustive — the compiler rejects a switch expression over an enum that misses a constant. The one-liner: "Statements do things; expressions produce values — and the compiler now enforces that I handled every case."

5. What are virtual threads, and why do they matter?

// platform thread: 1 OS thread each — ~10k threads is painful
Thread t = Thread.ofPlatform().start(() -> handle(request));

// virtual thread: JVM-managed, cheap — 1M threads is boring
Thread vt = Thread.ofVirtual().start(() -> handle(request));

// or with an executor, the migration-friendly way:
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
    exec.submit(() -> handle(request));
}

Answer: virtual threads are JVM-managed threads that don't map 1:1 to OS threads — creating a million of them is routine. They shine for blocking, I/O-bound workloads (web servers, DB calls): write simple blocking code, get reactive-level scalability. They do not make CPU-bound work faster — that's still core-count limited. The trap follow-up: "So should we rewrite everything?" — No: pin virtual threads with synchronized blocks carefully (pinning reduces their benefit), and CPU-bound pools still want platform threads.

6. What are text blocks?

String json = """
    {
      "orderId": "A-100",
      "amount": 250.00
    }
    """;

Answer: multi-line string literals with """ — no more concatenation or escaping for JSON, SQL, HTML in code. Incidental whitespace is stripped per the closing delimiter's indentation. The follow-up is usually practical: "How do you embed this in a real codebase?" — SQL queries and test fixtures are the canonical answers.

7. Scoped values and structured concurrency — one line each

Scoped values (Java 21 preview): immutable, inheritable context (like a safer ThreadLocal) that flows into child threads — built for virtual threads. Structured concurrency: treat a group of related tasks as one unit — if one fails or times out, the rest are cancelled together. You won't be grilled on these yet, but naming them signals you're current.

Quick-fire revision table

FeatureSinceOne-line answer
Records16Immutable data carriers; can't extend classes
Sealed classes17Closed type hierarchies; compiler-checked exhaustiveness
Pattern matching switch21Type test + bind + branch; handles null explicitly
Switch expressions14Switch returns a value; must be exhaustive
Text blocks15Multi-line strings without escaping
Virtual threads21Cheap JVM threads for blocking I/O workloads

In this series

  1. Java 17 to 21 Interview Questions: Records, Pattern Matching, Virtual Threads (this post) — records, pattern matching, virtual threads.
  2. Spring Boot Interview Questions and Answers (2026 Edition) — auto-configuration to actuators.
  3. Java Multithreading and Concurrency Interview Questions: Deep Dive — volatile, locks, deadlocks, pools.
  4. Microservices Interview Questions for Java Developers — decomposition, resilience, sagas.

More: Java Interview Prep hub — the full collection of Java interview questions on JavaMakeUse.

Comments

Popular posts from this blog

Java Banking Finance Services and Insurance (BFSI) domain interview questions

JSP Servlet Interview Questions For Freshers Series 1

Java program to check even or odd number