Java Record Patterns: Deconstruction, Nested Records, and switch Syntax
How Java 21 record patterns deconstruct record values, how nested patterns compose, and how guards, ordering, and exhaustiveness decide whether a pattern switch compiles.

A record pattern deconstructs a record value in place of a cast: obj instanceof Point(int x, int y) tests the type, invokes both accessors, and binds the results to new variables in one expression. Final since Java 21 (JEP 440), record patterns nest arbitrarily, so a Rectangle made of ColoredPoints made of Points comes apart in a single pattern whose shape mirrors the constructor calls that built it. Combined with pattern matching for switch (JEP 441), they replace the instanceof ladder and the visitor classes that data-shaped code used to need.
A record pattern is a deconstruction, not a cast
record Point(int x, int y) {}
static int sum(Object obj) {
if (obj instanceof Point(int x, int y)) {
return x + y; // no cast, no accessor calls in the body
}
return 0;
}The pattern names need not match the component names; Point(int a, int b) binds the same values under different names, in component order. var is allowed where the type is obvious: obj instanceof Point(var x, var y). Matching null never succeeds against a record pattern, so a top-level null falls through to the else instead of throwing.
The whole pattern matches or nothing does. That is what makes nesting useful:
record ColoredPoint(Point p, Color c) {}
record Rectangle(ColoredPoint upperLeft, ColoredPoint lowerRight) {}
static void describe(Rectangle r) {
if (r instanceof Rectangle(ColoredPoint(Point(var x, var y), var c),
var lowerRight)) {
System.out.println("corner " + x + "," + y + " is " + c);
}
}Nested record patterns fail as a unit: if upperLeft is null, or its p() returns null, or a component has the wrong runtime type, the entire instanceof is false. No branch of the pattern is partially bound, which is exactly the behaviour that removes the defensive null checks from deep navigation code.
switch turns the ladder into labels
sealed interface Shape permits Circle, Square, Rect {}
record Circle(Point center, int radius) implements Shape {}
record Square(Point topLeft, int side) implements Shape {}
record Rect(Point topLeft, Point bottomRight) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle(Point(var cx, var cy), var r) -> Math.PI * r * r;
case Square(Point(var x, var y), var s) -> (double) s * s;
case Rect(Point(var x1, var y1), Point(var x2, var y2)) ->
Math.abs((x2 - x1) * (y2 - y1));
};
}The same switch as a statement does not need a default here either, because Shape is sealed and the three permitted records cover every value — but exhaustiveness is required of the statement as well. A pattern switch statement that misses a case is a compile-time error, unlike a classic switch over an enum.
| Construct | Handles null | Checks exhaustiveness | Can use guards |
|---|---|---|---|
if (x instanceof T t) | false, no NPE | no | no |
if (x instanceof T(a, b)) | false, no NPE | no | no |
switch with pattern labels | only with case null | yes | yes, with when |
switch over constants only | only with case null (Java 21+) | no | no |
null, guards, and ordering
A switch still throws NullPointerException on a null selector unless a case null label exists, and default does not catch null. Fold both into one arm:
switch (shape) {
case null, default -> throw new IllegalArgumentException("no shape");
case Circle(Point(var cx, var cy), var r) when r > 0 -> area(r);
case Circle c -> throw new IllegalArgumentException("radius " + c.radius());
}Guards follow the pattern and see every variable the pattern bound; when replaces the && that preview releases used. Only pattern labels can be guarded — case "yes" when x > 1 does not compile.
Order is the whole semantics, because the first applicable label wins. A label is a compile error when a preceding label already covers everything it could match, which is why subtype order and unguarded-last order are enforced rather than advised:
switch (obj) {
case Integer i when i > 0 -> positive(); // guarded: does not dominate below
case Integer i -> nonPositive(); // fine after the guarded arm
case CharSequence cs -> text(cs);
case String s -> { } // error: dominated by CharSequence
}Constants belong at the top, guarded patterns next, unguarded patterns last. A guarded label is also treated as dominating a later constant arm — case Integer i when i != 0 dominates case 0 — because the compiler does not reason about guard expressions.
Generic records come apart with inferred arguments
A raw record pattern infers its type arguments from the selector, including in nested positions:
record Box<T>(T t) {}
static void unwrap(Box<Box<String>> boxes) {
if (boxes instanceof Box(Box(var s))) { // Box<Box<String>>(Box<String>(var s))
System.out.println(s.length());
}
}Type patterns keep the old rule and treat a raw name as raw (List l), so generic inferences apply only where a record pattern supplies the target type. If the runtime type cannot pin the argument down, write it explicitly rather than relying on inference.
Edge cases that decide whether the refactor is safe
1. Exhaustiveness analysis of nested components is not element-wise complete
record Pair<T>(T x, T y) {}
Pair<A> p; // class A {}, class B extends A {}
switch (p) { // not exhaustive: (A, A) is uncovered
case Pair<A>(A a, B b) -> { }
case Pair<A>(B b, A a) -> { }
}Two arms that cover the mixed cases say nothing about the arm where both components are the plain supertype. With a sealed component type the compiler can prove coverage from the permitted subtypes, which is one more reason to model data as sealed records instead of a class hierarchy with open extension.
2. A nested null component turns a match into a silent miss
record Wrapper(Point p) {}
Object value = new Wrapper(null);
if (value instanceof Wrapper(Point(var x, var y))) {
// never entered
} else {
// lands here, with no exception and no indication which level failed
}When a pattern fails you get one boolean, not a diagnosis. Log the outer type match separately (value instanceof Wrapper) if a missing printout would otherwise be blamed on the wrong layer.
3. Record patterns exist in two places only
They are allowed in instanceof and in switch labels, nowhere else: the enhanced-for header support was removed before Java 21 finalized, and catch (MyError(var code)) does not compile. Iterate and destructure inside the loop body instead.
4. Guards cannot rescue a dominated arm
A guard is opaque to dominance analysis, so putting the more specific arm after the general one fails even when the guard makes it look reachable. Reversing the two lines is rejected: an unguarded Circle c label dominates the guarded label with the same pattern, because every value that satisfies the guard already matches Circle c. A guard never makes a later arm reachable; only position does.
5. Pattern variables are scoped by flow, not by block
static int width(Shape s) {
if (!(s instanceof Rect(Point(var x1, var y1), Point(var x2, var y2)))) {
return 0;
}
return Math.abs(x2 - x1); // both bindings are in scope here
}The negation with an early return puts the matched variables in scope for the rest of the method, because the compiler proves they are assigned on every path that reaches the return. The guard-clause style works without a nested block, but only when the negative branch exits.
Common mistakes
| Error | Cause | Fix |
|---|---|---|
',' or ')' expected inside instanceof | building with --release 17 or older | build with a JDK 21 toolchain |
| "this case label is dominated by a preceding case label" | a broader type or a constant appears above a narrower arm | order constants, then guarded patterns, then unguarded patterns |
| "the switch statement does not cover all possible input values" | pattern switch statements must be exhaustive too | add the missing permitted subtype or a default |
NullPointerException from the switch | no case null and the selector was null | add case null or case null, default |
| "pattern type X is not compatible with selector" | the pattern cannot cast to the selector's static type | widen the selector or fix the model |
| record pattern rejected on a plain class | only record types deconstruct; getters do not count | convert the type to a record, or use a type pattern |
| variables "cannot find symbol" after a pattern | the arm ended, or the negative branch did not exit | keep the use inside the arm, or return early from the negation |
The practical ordering for a refactor: convert the data model to sealed records first, then replace instanceof ladders with record patterns, then move each ladder into a switch expression so the compiler starts enforcing exhaustiveness the moment the model gains a new case.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.