Lesson · Records, Sealed Types & Pattern Matching
Modern conveniences: sequenced collections and the feature-status check
14 min readOther Modern Language Features
Sequenced collections gave every ordered collection getFirst, getLast and reversed on JDK 21; var, text blocks and switch expressions matured long before. And string templates show why feature status is part of the feature.
Features age like produce
The modern Java shelf, with each feature's real status on a recent JDK:
| Feature | Landed | Status |
|---|---|---|
var | Java 10 | Final: local inference, nothing more |
| Switch expressions | Java 14 | Final: arrow cases, yield |
| Text blocks | Java 15 | Final: multiline strings |
| Records | Java 16 | Final (covered in this chapter) |
| Sealed types | Java 17 | Final (covered in this chapter) |
| Pattern matching (switch, records) | Java 21 | Final (covered in this chapter) |
| Sequenced collections | Java 21 | Final: getFirst, getLast, reversed |
| String templates | Java 21 | Preview, then withdrawn: never final |
Predict: which row is the odd one out? String templates: previewed in Java 21, removed from the roadmap later without ever finalising. The lesson: a feature's status (preview, final, withdrawn) is part of the feature, and version-specific advice ages fastest of all.
Sequenced collections: first, last, reversed
JDK 21 gave ordered collections a shared vocabulary instead of per-type idioms:
List<String> steps = List.of("read", "plan", "write"); System.out.println(steps.getFirst()); // read System.out.println(steps.getLast()); // write System.out.println(steps.reversed()); // [write, plan, read]
getFirstandgetLastwork on anyList,Deque, and orderedSet(likeLinkedHashSet), without per-type quirks.reversed()returns a reversed view in constant time: no copying, and it updates if the underlying collection does.DequegainedaddFirst/addLastsymmetry, and the three interfaces (SequencedCollection,SequencedSet,SequencedMap) unify the family.- Verified on JDK 21:
List.ofandLinkedHashSetboth answergetFirst, and.reversed()prints the expected order.
A shared vocabulary removes folklore. The old list of per-collection tricks (list.get(0), deque.getFirst(), iterating a set for its first element) collapses into one API every ordered collection now speaks.
Feature shelf · status is part of the feature
pick a featuregetFirst() → read getLast() → write reversed() → [write, plan, read]
A constant-time reversed view, and one vocabulary for every ordered collection: no more per-type folklore.
The final features' outputs were produced by javac 21 and a real run; the withdrawn entry states its status rather than running.
var, text blocks, switch expressions: the recap
Three conveniences worth having in muscle memory, with their exact rules:
- `var` is local inference: locals (and loop variables) with an initialiser, type inferred from the right side; never fields, never parameters, never a substitute for naming a type that is not obvious.
- Text blocks are raw readability: triple quotes, automatic stripping of incidental indentation,
\swhen a trailing space matters, and.formatted()/String.formatfor interpolation; verified: a two-line SQL block counts 2 lines. - Switch expressions produce values: arrow cases with no fall-through,
yieldfor block bodies, and exhaustiveness checks over sealed families; verified:switch (name)returningadminfor"Ada".
All three are final and boring now, which is the goal. Conveniences stop being news; the latest additions (sequenced collections) are the same kind of small, permanent improvement.
The string templates status check
A lesson in reading feature status honestly:
- Previewed in Java 21:
STR."Hello \{name}"with template processors promised safer interpolation than concatenation. - Then withdrawn: the design was pulled from the roadmap rather than finalised; there is no string-template feature in current Java, preview or otherwise.
- What to use instead:
String.format/formattedfor simple cases,MessageFormatfor localisation, and libraries where the requirements are richer. - The general habit: before adopting or teaching any language feature, check its status for the exact version in front of you, and treat preview features as movable.
Previews are a design process, not a release queue. Most previews (records, pattern matching) finalised; some do not. Building against one commits you to rereading its status every release, which is fine for experiments and expensive for production code.
The modern-features playbook
Using version-gated features well, in order:
- Name the version you target and verify each feature's status there; remember the templates example.
- Reach for the boring wins freely: var for obvious locals, text blocks for multiline text, switch expressions over statement switches.
- Use sequenced collections' vocabulary (
getFirst,reversed) instead of per-type folklore. - Adopt preview features only in experiments, with a written note about the risk.
- When a feature lands final, fold it into habit; when it changes, the status check is a one-line habit that never bites twice.
Small permanent improvements, adopted on evidence. The modern-Java habits worth keeping are the ones that survived: inference, readability and expressed intent, each verified against the version actually running.
Sequenced collections speak for every ordered collection; check status before adopting anything
JDK 21's getFirst, getLast and reversed unify ordered collections behind one API. var, text blocks and switch expressions are long-final conveniences worth routine use. String templates previewed in 21 and were withdrawn, which is the standing reminder: verify a feature's status in your exact version before designing around it.
Interview angles
What did sequenced collections add?+
A shared API for ordered collections: getFirst, getLast and a constant-time reversed view on List, Deque and ordered Sets (and SequencedMap for order-aware maps), final in JDK 21.
The interfaces (SequencedCollection, SequencedSet, SequencedMap) unify what previously differed per type. Deque also gained addFirst/addLast symmetry, and reversed() is a view: it stays in sync with the underlying collection without copying.
List<String> steps = List.of("read", "plan", "write"); steps.getFirst(); // read steps.reversed(); // [write, plan, read]
Common misconception: That reversed() copies the list. It is a view in constant time; use it for iteration order, not as a snapshot.
Follow-up: Where would a copy still be required?
What are var's limits, exactly?+
Locals and loop variables with an initialiser; the type is inferred from that right side. Never fields, parameters or return types, and never a way to hide an unclear type.
Verified trivia: var name = "Ada" is a String; the compiler does the typing. The readability rule is the load-bearing one: var should delete noise from an obvious right side, not the reader's ability to know the type.
var name = "Ada"; // String, obvious name.toUpperCase(); // ADA
Common misconception: That var makes Java dynamic. It is a compile-time abbreviation: the inferred type is fixed, and the compiler knows it exactly.
Follow-up: Which three declaration positions can never use var?
What do text blocks cost and save?+
They save concatenation noise for multiline text (SQL, JSON, HTML) and strip incidental indentation automatically; they cost awareness of trailing characters (\s) and of the fact that formatting still uses formatted() or String.format.
The verified example: a two-line SQL block reports exactly two lines via lines().count(). The block is still a plain String at runtime; there is no new type or template processing behind the quotes.
String sql = """ SELECT name FROM users """;
Common misconception: That text blocks interpolate variables. They do not; they are purely about readability of literals.
Follow-up: Which character sequence preserves a trailing space in a text block?
What happened to string templates?+
Previewed in Java 21 (STR."Hello {name}"), then withdrawn from the roadmap: the design never finalised, and current Java has no string-template feature.
The withdrawal is the teaching moment: preview features are moveable designs, and adoption carries a standing obligation to recheck status each release. For interpolation today: formatted(), String.format, MessageFormat or a small library.
"value: %d".formatted(7); // value: 7 (the reliable route)
Common misconception: That anything once previewed eventually lands. Some designs are pulled; templates are the standing counterexample to 'just wait for previews to finalise'.
Follow-up: What habit protects a team from building on a withdrawn preview?
Which of these features are final, and since when?+
var (10), switch expressions (14), text blocks (15), records (16), sealed (17), pattern matching and sequenced collections (21): all final. String templates: previewed (21) then withdrawn.
The list is deliberately boring, which is the point: features stop making news when they are final, and the news cycle belongs to previews that may vanish. Version-pinning the list makes upgrade decisions about features rather than headlines.
// JDK 21 verified in this lesson: List.of("a", "b").getFirst(); // a "x: %d".formatted(1); // x: 1
Common misconception: That 'modern Java' means the newest preview. It means the final features your version ships, used deliberately.
Follow-up: Where do you check a feature's current status authoritatively?