Java Record Patterns: Deconstruction, Nesting and switch (OCP 21)
Record patterns for the OCP 21 exam: deconstructing records with instanceof, the component rules, how nested pattern types match at run time, nested record patterns, var and generics in patterns, record patterns in switch with when guards, exhaustiveness, and what changed in Java 22 to 25.
kvi5hnuCode Sprout team member7 min readOn this page
Article 11 showed type patterns: obj instanceof String s tests a type and binds a variable in one step. Java 21 adds record patterns (JEP 440). A record pattern tests that an object is a particular record and pulls out its components into variables. This is called deconstructing the record.
A first record pattern
record Parcel(String code, int grams) { }
Object o = new Parcel("PX-7", 850);
if (o instanceof Parcel(String code, int weight)) {
System.out.println(code + " weighs " + weight + " g"); // PX-7 weighs 850 g
}
Parcel(String code, int weight) isn't a declaration. It's a pattern with the same shape as the record header. If o is a Parcel, its accessors are called and the results are bound to code and weight. These pattern variables follow the same flow-scoping rules as type patterns (article 11). For example, if (!(o instanceof Parcel(var c, var g))) return; leaves c and g in scope afterwards. null never matches a record pattern.
The rules for record patterns
- List every component. You can't list only some of them:
Parcel(String code)fails with "incorrect number of nested patterns". - Keep declaration order.
Parcel(int g, String c)fails because the types don't line up. - The variable names are your choice. They don't have to match the component names.
- Each nested pattern type must be compatible with the component type. It can be the same type, a supertype, or a subtype that might match at run time. An impossible type is a compile error.
- Primitive components need their exact type, or
var. Neither widening nor boxing is applied:Parcel(String c, long g)andParcel(String c, Integer g)both fail in Java 21. (JDK 23 to 25 report this as "primitive patterns are a preview feature", see the end of the article.) - A record pattern can't also be named.
o instanceof Parcel(String c, int g) pdoesn't compile in Java 21. Either name the whole record (instanceof Parcel p) or deconstruct it. (Named record patterns existed only in the first preview, in Java 19, and were removed in Java 20.) - Every pattern variable needs a distinct name. Reusing one gives "variable name is already defined".
if (o instanceof Parcel p) { } // type pattern: fine
if (o instanceof Parcel(Object c, int g)) { } // Object is a supertype of String: fine
if (o instanceof Parcel(CharSequence c, var g)) { } // var g is int: fine
if (o instanceof Parcel(String c, long g)) { } // DOES NOT COMPILE: no widening
if (o instanceof Parcel(String c, int g) p) { } // DOES NOT COMPILE
Matching happens at run time, component by component
A record pattern matches only if the record type matches and every nested pattern matches its component's actual value. For components declared as Object (or another broad type), the nested type acts like an instanceof test:
record Crate(Object contents) { }
Crate a = new Crate("apples");
Crate b = new Crate(Integer.valueOf(12));
Crate c = new Crate(null);
a instanceof Crate(Object x) // true
a instanceof Crate(String x) // true
a instanceof Crate(Integer x) // false: compiles, but "apples" isn't an Integer
b instanceof Crate(String x) // false
b instanceof Crate(Integer x) // true
c instanceof Crate(Object x) // true: Object (or var) matches a null component
c instanceof Crate(String x) // false: a narrower type never matches null
A nested pattern whose type covers the component type fully (the same type, a supertype or var) is unconditional, so it also matches a null component. A narrower nested type behaves like instanceof and rejects null.
If the component type makes a match impossible, the code doesn't compile. With record Crate(Integer contents), the test instanceof Crate(String x) fails with "Integer cannot be converted to String".
Nested record patterns
When a component is itself a record, you can deconstruct it in place:
record Point(int x, int y) { }
record Rect(Point topLeft, Point bottomRight) { }
if (shape instanceof Rect(Point(int x1, int y1), Point p2)) {
System.out.println(x1 + "," + y1 + " to " + p2);
}

You can expand one component and leave the other as a plain type pattern, as above, or expand every level. Every variable must still have a unique name, so Rect(Point(int x, int y), Point(int x, int y)) fails. Use x1, y1, x2, y2 instead.
var and generics in record patterns
var can replace any nested pattern's type. It infers exactly the component type, so it always matches, including null:
record Bag(String owner, List<String> items) { }
record Trip(Bag first, Bag second) { }
if (t instanceof Trip(var a, Bag(var who, var stuff))) {
// a is Bag, who is String, stuff is List<String>
}
With generic component types, the nested type must be a legal cast target, following the same reasoning as generic method overriding (chapter 9):
t instanceof Trip(Bag(var w, Object s), var b) // OK
t instanceof Trip(Bag(var w, List s), var b) // OK (raw type, with a rawtypes warning)
t instanceof Trip(Bag(var w, List<?> s), var b) // OK
t instanceof Trip(Bag(var w, List<? extends Object> s), var b) // OK
t instanceof Trip(Bag(var w, ArrayList<String> s), var b) // OK: may match at run time
t instanceof Trip(Bag(var w, List<> s), var b) // DOES NOT COMPILE: no diamond in patterns
t instanceof Trip(Bag(var w, List<Object> s), var b) // DOES NOT COMPILE: List<String> ≠ List<Object>
The pattern variable has the pattern's type, not the component's. With raw List s, s.getFirst() returns Object, so s.getFirst().toLowerCase() doesn't compile.
For a generic record, the type arguments are inferred: with Box<String> b, b instanceof Box(var s) makes s a String.
Record patterns in switch
Record patterns work as case labels, optionally with when guards, and they follow the switch-pattern rules from article 13:
record Signal(Object value) { }
static long decode(Signal s) {
return switch (s) {
case Signal(Long l) -> l + 1;
case Signal(Integer i) -> i + 10;
case Signal(Number n) -> n.intValue() + 100;
case Signal(Object o) -> -1; // covers everything else, including a null value
};
}
decode(new Signal(1)); // 11
decode(new Signal(2L)); // 3
decode(new Signal(3.0)); // 103
decode(new Signal("x")); // -1
decode(null); // NullPointerException: switch on null without case null
The same rules apply here:
- Exhaustiveness. Without a
default, the cases must cover every possibility. In the example above,Signal(Object o)does that. Leaving it out, with nodefault, fails with "does not cover all possible input values". - Dominance. A more general pattern can't come before a more specific one.
case Signal(Object o)placed beforecase Signal(String t)fails with "this case label is dominated by a preceding case label". - Guards use the pattern's type.
case Signal(Object o) when o.doubleValue() > 0fails, becauseObjecthas nodoubleValue().
With sealed hierarchies, exhaustiveness is checked across combinations of components:
sealed interface Coin permits Heads, Tails { }
record Heads() implements Coin { }
record Tails() implements Coin { }
record Toss(Coin first, Coin second) { }
static int score(Toss t) {
return switch (t) { // exhaustive: every combination covered
case Toss(Heads h, Coin c) -> 1;
case Toss(Tails a, Heads b) -> 2;
case Toss(Tails a, Tails b) -> 3;
};
}
Remove the third case, and the compiler reports that the switch doesn't cover all input values.
What's current
- Record patterns are final in Java 21 (JEP 440).
- Java 22 finalized unnamed patterns (
Parcel(String code, _)). Primitive widening inside record patterns is part of the primitive-patterns preview, not of Java 21 or 25.
Exam traps from this article
A complete example
Shapes are a sealed interface of records built from Point records. One exhaustive switch deconstructs them with nested patterns and when guards. A generic Labeled record shows run-time matching on an Object component.
import java.util.List;
public class Solution {
record Point(int x, int y) { }
sealed interface Shape permits Circle, Rect, Line { }
record Circle(Point center, double radius) implements Shape { }
record Rect(Point topLeft, Point bottomRight) implements Shape { }
record Line(Point from, Point to) implements Shape { }
record Labeled<T>(String label, T value) { } // generic record
// Exhaustive switch over a sealed type, with nested record patterns
static String describe(Shape s) {
return switch (s) {
case Circle(Point(var x, var y), double r) when r == 0 ->
"a dot at (" + x + "," + y + ")";
case Circle(Point c, double r) ->
"circle r=" + r + " around " + c;
case Rect(Point(int x1, int y1), Point(int x2, int y2)) ->
"rect " + Math.abs(x2 - x1) + "x" + Math.abs(y2 - y1);
case Line(Point(int x1, int y1), Point(int x2, int y2)) when x1 == x2 ->
"vertical line at x=" + x1;
case Line l -> "line " + l.from() + " -> " + l.to();
};
}
// Component typed Object: the nested pattern type decides whether it matches
static String unwrap(Labeled<Object> item) {
if (item instanceof Labeled<Object>(String label, Integer n)) {
return label + ": integer " + (n + 1);
}
if (item instanceof Labeled<Object>(var label, String text) && !text.isBlank()) {
return label + ": text '" + text.strip() + "'";
}
return item.label() + ": something else (" + item.value() + ")";
}
public static void main(String[] args) {
List<Shape> shapes = List.of(
new Circle(new Point(2, 3), 0),
new Circle(new Point(0, 0), 1.5),
new Rect(new Point(1, 5), new Point(4, 1)),
new Line(new Point(7, 0), new Point(7, 9)),
new Line(new Point(0, 0), new Point(3, 4)));
for (Shape s : shapes) {
System.out.println(describe(s));
}
Object o = new Point(5, 8);
if (o instanceof Point(int x, int y) && x < y) { // deconstructed variables in scope
System.out.println("point below the diagonal: " + x + "<" + y);
}
System.out.println(unwrap(new Labeled<>("qty", 41)));
System.out.println(unwrap(new Labeled<>("note", " fragile ")));
System.out.println(unwrap(new Labeled<>("weight", 2.5)));
System.out.println(unwrap(new Labeled<>("empty", null)));
}
}
Output:
a dot at (2,3)
circle r=1.5 around Point[x=0, y=0]
rect 3x4
vertical line at x=7
line Point[x=0, y=0] -> Point[x=3, y=4]
point below the diagonal: 5<8
qty: integer 42
note: text 'fragile'
weight: something else (2.5)
empty: something else (null)
Points to notice:
- The guarded
Circle(...) when r == 0case comes before the unguardedCirclecase, so it isn't dominated. case Line l(a plain type pattern) after the guardedLinecase makes the switch exhaustive, and nodefaultis needed, becauseShapeis sealed.- The
Rectcase expands both corners, with four distinct variable names. - In
unwrap,Labeled<Object>(String label, Integer n)matches only when the value really is anInteger. ADoubleand anullvalue fall through to the last line. instanceof Point(int x, int y) && x < yuses the deconstructed variables in the same condition.
Common questions
Do record patterns call the accessors or read the fields? They call the accessor methods. An overridden accessor's return value is what gets matched and bound.
Can I deconstruct ordinary classes? Not in Java 21. Only records have the "header" a pattern can mirror. (Deconstruction patterns for classes are being explored for future Java versions.)
When should I use var in a nested pattern?
When you only want to bind the value and don't need a type test. var always matches, including null.
Summary
obj instanceof Rec(T1 a, T2 b)tests the record type and binds every component, in order, to new variables.- Nested types must be compatible with their components. Primitive components need the exact primitive type or
var. - At run time a narrower nested type acts like
instanceof. An unconditional one (the same type, a supertype orvar) also matchesnull. - Record patterns nest to any depth. Variable names must be unique. No diamond or incompatible generics.
- In
switch, record patterns follow the exhaustiveness, dominance andwhenrules, which work especially well with sealed types.
Practice quiz
Test yourself with the record patterns quiz: 10 exam-style questions with explanations.
Previous: Java Records: Compact Constructors, Accessors and Customization (OCP 21)
Next: Java Nested Classes: Inner Classes and Static Nested Classes (OCP 21)
Related reading
- Java Sealed Classes and Interfaces: sealed, permits, final and non-sealed (OCP 21)
- Java Pattern Matching for switch: Type Patterns, when Guards, null and Record Patterns (OCP 21)
- Java switch Statements and switch Expressions: case Values, yield and Exhaustiveness (OCP 21)
- Java if/else, Pattern Matching for instanceof and Flow Scoping (OCP 21)
- Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.