Java 17 and Java 21 Interview Questions: Records, Sealed Classes, Pattern Matching and Virtual Threads
By Preeti Verma
Most Java interviews used to stop at Java 8. In 2026 that is changing. Many teams have moved to Java 17 or 21, and interviewers use the newer features to find out whether you keep your skills current or stopped learning at streams and lambdas.
You do not need to memorise every release. You need to explain a handful of features clearly, say why they exist, and know when you would use them. This guide covers the ones that come up most.
A quick map of the releases
Java 8, 11, 17 and 21 are the long-term support (LTS) versions most companies standardise on. Features arrive in preview, then become final. When an interviewer says "Java 17", they usually mean everything added between 9 and 17. Java 21 adds a few more headline features, mainly virtual threads and pattern matching for switch.
1. What is a record, and when would you use one?
A record is a compact way to declare an immutable data carrier. This one line gives you private final fields, a constructor, accessors, equals, hashCode and toString:
public record Point(int x, int y) {}
Points that show you understand it:
- Records are shallowly immutable. If a record holds a
List, the list itself can still change unless you copy it. - A record cannot extend another class, but it can implement interfaces.
- You can add a compact constructor to validate input, and extra methods.
- Good uses: DTOs, API responses, map keys, tuples returned from a method.
- Poor fit: JPA entities, which need mutable state and a no-argument constructor.
2. What are sealed classes?
A sealed class or interface restricts which classes may extend it, using permits:
public sealed interface Shape permits Circle, Square {}
The point is control. You model a closed set of types, and the compiler knows every possibility. That pays off with pattern matching: a switch over a sealed type can be checked for completeness, so you do not need a default branch, and adding a new subtype produces a compile error wherever you forgot to handle it. A good one-line answer: "sealed types let me model a closed set of cases and let the compiler check I handled them all."
3. Pattern matching for instanceof
Before, you checked the type, then cast:
if (obj instanceof String) { String s = (String) obj; ... }
Now the cast is built in:
if (obj instanceof String s && s.length() > 3) { ... }
It is shorter and removes a class of mistakes. Mention that the variable s is only in scope where the check is known to be true.
4. Switch expressions and pattern matching for switch
Switch can now return a value, uses arrows, and has no fall-through:
String label = switch (day) {
case SATURDAY, SUNDAY -> "Weekend";
default -> "Weekday";
};
In Java 21, switch can also match on types and patterns, including a guard with when:
static String describe(Object o) {
return switch (o) {
case Integer i when i > 10 -> "big int";
case Integer i -> "int";
case String s -> "text of length " + s.length();
default -> "something else";
};
}
Be ready for the follow-up: "What happens if you do not cover every case?" For an expression over a sealed type or enum, the code does not compile unless it is exhaustive. That is the safety benefit.
5. Record patterns (Java 21)
You can take a record apart directly inside a pattern:
if (shape instanceof Rectangle(double w, double h)) { ... }
It combines nicely with sealed types for clean, readable branching over data.
6. Text blocks
Text blocks use triple quotes for multi-line strings, which makes embedded JSON, SQL and HTML readable without escape characters and \n noise. A good answer notes that incidental indentation is stripped, based on the closing delimiter's position.
7. var, and where it is a bad idea
var (Java 10) lets the compiler infer a local variable's type. It does not make Java dynamically typed. Use it when the type is obvious on the right-hand side (var users = new ArrayList<User>()), and avoid it when it hides what the value is (var result = service.process()). Interviewers often ask for the downside: it can reduce readability when overused.
8. Virtual threads (Java 21)
This is the headline Java 21 question. Virtual threads are lightweight threads managed by the JVM, not by the operating system. You can create very many of them, and when one blocks on I/O the JVM runs another on the same carrier thread.
What a strong answer says:
- They let you write simple blocking code that scales to many concurrent tasks, which suits request-per-thread servers that mostly wait on databases and network calls.
- They do not make CPU-bound work faster. For that, you still need cores.
- You do not pool them. They are cheap, so create one per task, for example with
Executors.newVirtualThreadPerTaskExecutor(). - Watch for pinning: blocking inside a
synchronizedblock can hold on to the carrier thread. PreferReentrantLockin hot paths. (This has improved in later releases, but it is a good point to know.) - Shared resources such as database connections still limit throughput, so a huge number of threads does not remove that bottleneck.
For the older concurrency fundamentals this builds on, see our Java multithreading and concurrency interview questions.
9. Sequenced collections (Java 21)
Collections that have a defined order, such as List, Deque, LinkedHashSet and LinkedHashMap, now share a SequencedCollection interface with getFirst(), getLast(), addFirst(), addLast() and reversed(). It removes awkward workarounds like list.get(list.size() - 1). A short mention shows you read the release notes.
10. Smaller features worth knowing
Stream.toList()(16) returns an unmodifiable list, shorter thancollect(Collectors.toList()).- Helpful NullPointerExceptions (14) name exactly which variable was null.
Optional.orElseThrow()without arguments, andisEmpty().- Immutable factories:
List.of,Set.of,Map.of, which reject nulls and cannot be changed.
Questions to practise out loud
- When would you choose a record over a class, and when would you not?
- How do sealed classes and switch pattern matching work together?
- What problem do virtual threads solve, and what do they not solve?
- Would you rewrite an existing Java 8 service to use these features? Why or why not? (A good answer is "only where it makes code clearer, with tests in place, not just to use new syntax".)
- What is the difference between
List.ofandCollections.unmodifiableList?
For a refresher on the base layer, read our Java 8 interview questions on streams, lambdas and Optional and the broader Core Java questions for experienced developers.
Practise this on GenQuest
- Start a voice mock interview: answer out loud to an AI interviewer that knows your resume and the role, get follow-up questions, then read a scored report with a question-by-question review. Your first 15-minute interview is free.
- Open the question banks: Core Java scenarios, Blind 75 and NeetCode 150, high-level and low-level design questions, and company-wise sheets, with a free preview and progress tracking.
- Ask the AI Coach: paste any question you are stuck on and get it explained in plain words, with a short answer you could say in an interview. See how it works in our AI Coach introduction.
FAQ
Do I need to know all of this for a Java 8 project? If your project uses Java 8, you will still be asked about it. Newer features show curiosity, and many interviewers ask which Java version you would pick for a new service.
Which version should I say I would choose for a new project? A recent LTS release (17 or 21), because of security updates and the features above. Be ready to explain that the framework and library support need to match.
Are preview features asked in interviews? Occasionally, as a conversation about where Java is heading. Know the idea, and say clearly which parts are final and which are not.
The takeaway
Learn records, sealed classes, pattern matching, text blocks and virtual threads well enough to explain what problem each solves and where it does not help. A calm, honest answer about trade-offs beats listing syntax.