Modern Java: records, sealed types, pattern matching
Use Java 17–21 features to write less boilerplate.
By Invicly Tech, , in Backend Java Development. About 12 minutes to read.
In short
Java 17 to 21 added records, sealed types and pattern matching. Together they cut boilerplate and let the compiler check that every case of a type hierarchy is handled.
Explained simply
Java changed a lot between Java 8 and Java 21. Many new features have one goal: let you say more with less code, while the compiler still checks everything. If you learned Java long ago, modern code may look surprisingly short.
A record is a class whose only job is to carry data. You write record Point(int x, int y) {} and Java creates the constructor, the accessors x() and y(), equals, hashCode and toString. Records are perfect for DTOs (data transfer objects), events and results.
A sealed type is a closed family. You say exactly which classes are allowed to be its children, and nobody else can join. Because the compiler knows the full list, it can check that your code handles every member of the family.
Pattern matching lets you test what type something is and use it in one step. Combined with switch, you can write clean code like: if it is a Circle, do this; if it is a Square, do that. Forget a case and the compiler tells you.
Press Play on a diagram to walk through it one step at a time.
- Write fields, constructor, getters
- Hand-write equals and hashCode
- Hand-write toString
- Often 40+ lines
- record Point(int x, int y) {}
- Fields are final, immutable
- equals, hashCode, toString generated
- One line
- record Circle
- double r
- record Square
- double side
- No other implementations
- switch can be exhaustive
- No default branch needed
- 1Evaluate the value
The selector expression runs once
- 2Is it null?
Use case null, otherwise NullPointerException
- 3Try cases top to bottom
Type must match and the guard must be true
- 4First match wins
Its pattern variables are bound
- 5Run that branch
The result is the switch value
In depth
Records beyond one line
A record's components become private final fields, and its accessors use the component names: point.x(), not getX(). You can add your own methods, static factory methods and static fields. You can implement interfaces. You cannot extend another class, add instance fields, or extend a record, because records are final.
To validate data, write a compact constructor: record Range(int start, int end) { Range { if (start > end) throw new IllegalArgumentException(); } }. It runs before the fields are assigned, and you can even reassign the parameters there, for example to trim a string. Records are only shallowly immutable: a List component can still be changed by whoever holds it, so copy it with List.copyOf in the compact constructor.
Records work well as Spring DTOs and JSON bodies (Jackson supports them) but not as JPA entities, which need a no-argument constructor and mutable fields.
- Accessors: p.x(), p.y()
- Compact constructor for validation
- List.copyOf for deep-ish immutability
Sealed types and their three kinds of children
You declare a sealed class or interface with a permits list: sealed interface Shape permits Circle, Square. If all children are in the same source file, you can leave out permits and the compiler works it out. The children must be in the same module, or in the same package when you do not use modules.
Every permitted child must state how it continues the hierarchy. final means it can have no children of its own; records and enums are implicitly final. sealed means it has its own permits list. non-sealed opens that branch again so any class may extend it, which is useful when a library wants one extension point. This forced choice keeps the whole hierarchy known to the compiler, except where you clearly opted out.
- final class Car
- No subclasses at all
- Records are final automatically
- sealed class Truck permits Van
- Lists its own children
- Still fully known to the compiler
- non-sealed class Bike
- Anyone may extend it
- Exhaustive checks still work at this level
Pattern matching for instanceof
The old style tested a type and then cast: if (o instanceof String) { String s = (String) o; ... }. Since Java 16 you write if (o instanceof String s) and s is ready to use. You can combine it with conditions: if (o instanceof String s && !s.isBlank()). It does not work with ||, because then s might not be set.
The binding variable follows flow scoping: it exists wherever the compiler can prove the test passed. So this works: if (!(o instanceof String s)) return; followed by s.length() on the next line. This pattern also makes equals methods shorter: return o instanceof Money m && cents == m.cents && currency.equals(m.currency).
Switch with patterns, guards and records
Java 21 lets switch match on types. case Circle c -> runs when the value is a Circle and binds c. A guard adds a condition: case Circle c when c.r() > 100 ->. Record patterns can take a record apart in place: case Point(int x, int y) -> gives you x and y directly, and patterns can nest.
Cases are tested from top to bottom, so specific cases must come before general ones. The compiler rejects a case that an earlier one dominates, such as case Circle c before case Circle c when .... A switch normally throws NullPointerException on null, but you may add case null ->. On a sealed type, a switch that covers every permitted subtype is exhaustive and needs no default. If someone later adds a subtype, every such switch fails to compile until it is handled, which is exactly the safety you want.
- case Type t when condition -> adds a guard
- case Point(int x, int y) -> deconstructs a record
- case null -> handles null explicitly
- Avoid default on sealed switches so new cases are caught
A short timeline of modern Java
Features usually arrive as previews first and become final a few releases later. You only need the final versions. Java 10 added var for local variables. Java 14 made switch expressions final and added helpful NullPointerException messages that name the exact null variable. Java 15 brought text blocks with triple quotes. Java 16 finalised records and pattern matching for instanceof. Java 17, an LTS release, finalised sealed classes. Java 21, the next LTS, finalised record patterns, pattern matching for switch, virtual threads and sequenced collections. Java 22 added unnamed variables, so you can write _ for a value you do not use, as in catch (Exception _). Java 25 is the LTS after 21.
- 1Java 14
Switch expressions, helpful NPE messages
- 2Java 15
Text blocks
- 3Java 16
Records, instanceof patterns
- 4Java 17 LTS
Sealed classes
- 5Java 21 LTS
Switch patterns, record patterns, virtual threads
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Replace POJOs with records~1h
- 2Model hierarchies with sealed types~1h
- 3Use pattern matching for instanceof~1h
- 4Write switch expressions with patterns~1h
Key points
- Records are immutable data carriers with generated accessors like point.x().
- Sealed types list exactly which classes may extend or implement them.
- Pattern matching for instanceof binds a typed variable: if (o instanceof String s).
- Switch expressions with type patterns (Java 21) are checked for exhaustiveness on sealed types.
Key terms
Tap a card to flip it. 0/5 known
Examples
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Square sq -> sq.side() * sq.side();
}; // no default: the compiler knows all cases
}
Object o = "hello";
if (o instanceof String str && str.length() > 3) {
System.out.println(str.toUpperCase());
}A validated Money record
You want a Money type that can never hold a negative amount or a missing currency. Step 1: declare a record with two components. Step 2: add a compact constructor that checks the rules; it runs on every creation, so no invalid Money can exist. Step 3: add behaviour as normal methods; plus returns a new Money because records are immutable. Step 4: equals and hashCode come for free, so Money works as a map key.
record Money(long cents, String currency) {
Money {
if (cents < 0) throw new IllegalArgumentException("negative amount");
Objects.requireNonNull(currency, "currency");
currency = currency.toUpperCase();
}
Money plus(Money other) {
if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
return new Money(cents + other.cents, currency);
}
}
// new Money(500, "eur").plus(new Money(250, "EUR")) -> Money[cents=750, currency=EUR]Modelling payment results with a sealed type
A payment can be approved, declined or fail. Step 1: model each outcome as a record that carries exactly the data it needs. Step 2: seal the interface so these are the only outcomes. Step 3: switch with record patterns to pull out fields, and a guard to treat retryable failures differently. The guarded case must come before the plain Failed case. Step 4: there is no default, so adding a new outcome later breaks the build here until you handle it.
sealed interface PaymentResult permits Approved, Declined, Failed {}
record Approved(String txId, long cents) implements PaymentResult {}
record Declined(String reason) implements PaymentResult {}
record Failed(Exception error, boolean retryable) implements PaymentResult {}
static String message(PaymentResult r) {
return switch (r) {
case Approved(String id, long cents) -> "Paid " + cents / 100.0 + " (tx " + id + ")";
case Declined(String reason) -> "Card declined: " + reason;
case Failed f when f.retryable() -> "Temporary problem, please retry";
case Failed f -> "Payment failed: " + f.error().getMessage();
};
}Quick reference
- record Point(int x, int y) {} gives a constructor, p.x(), equals, hashCode, toString
- Compact constructor Point { ... } validates before fields are set
- Every child of a sealed type must be final, sealed or non-sealed
- if (o instanceof String s && !s.isBlank()) binds and tests in one step
- case Circle c when c.r() > 10 -> adds a guard to a pattern
- case Point(int x, int y) -> deconstructs a record in a switch
- Leave out default on sealed switches so new subtypes cause compile errors
- Records suit DTOs and events; JPA entities still need normal classes
Common mistakes
- Putting mutable lists in a record and assuming the record is fully immutable.
- Adding a default branch to a sealed switch, which hides missing new cases.
- Trying to extend a record; records are implicitly final.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Turn this class into a record and add a method distanceTo(Point other): a class Point with final int x and y, a constructor, getters, equals and hashCode.
- Exercise 2medium
Write record Range(int start, int end) that rejects start > end, plus methods length() and contains(int n).
- Exercise 3hard
Model arithmetic expressions as a sealed interface Expr with records Num(int value), Add(Expr left, Expr right) and Mul(Expr left, Expr right). Write int eval(Expr e) with a pattern switch and no default.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Can I use records with Spring Boot and Jackson?
- Yes. Records work as request and response bodies, configuration properties and query projections. Only JPA entities still need regular classes.
- Do I need Java 21 for these features?
- Records need Java 16+, sealed types Java 17+, and pattern matching for switch plus record patterns Java 21+. Using Java 21 or newer gives you all of them as final features.
- Can a record have extra fields?
- Not instance fields; all state must be in the components. Static fields and any number of methods are allowed.
- Is pattern matching slower than instanceof and casts?
- No meaningful difference. The compiler and JIT produce efficient type checks, so choose it for clarity.