Record patterns
A record pattern tests that a value is a given record and binds its components to variables in the same step. Patterns nest, take guards, and with sealed types give switches the compiler checks for completeness. This page explains what a match actually does, then shows patterns in instanceof and switch, on an expression tree, on generic records, and the null and exception rules.
Contents
What a record pattern does Deconstructing with instanceof Record patterns in switch Nested patterns on a tree: simplifying expressions Generic records and type tests on components Accessor calls, null components and MatchException Exhaustiveness and dominance, checked by the compiler Choosing between patterns, accessors and visitors
What a record pattern does
Before Java 21, reading the values out of an ObjectPointinstanceofobj instanceof Point(int x, int y)objPointxy
Matching a value vPoint(int x, int y)
- If
isv , the pattern does not match. A record pattern never matchesnull .null - If
is not av , it does not match.Point - Otherwise the JVM calls the accessor for each component,
andv.x() , and matches each result against the nested pattern (v.y() ,int x ). A nested pattern can itself be a record pattern, which is how patterns reach several levels into a structure.int y
Two details follow from step 3. The values come from the accessors, so an overridden accessor's result is what you get, and an exception thrown by an accessor surfaces as MatchExceptionvar bShape bnull
| Form | Example | Matches a null | Best for |
|---|---|---|---|
| Explicit types | Point(int x, int y) | Primitives cannot be null | Readability when types are short |
var | Point(var x, var y) | Yes | Long or generic component types |
| Nested record pattern | Line(Point(var a, var b), var end) | No, for the nested part | Tree and message structures |
| Narrower type test | Box(String s)Box<Object> | No | Dispatching on a component's runtime type |
| Guarded case | case Rect(var w, var h) when w == h | Same as the pattern | Conditions on the values |
| Unnamed pattern | Point(var x, _) | Yes | Ignoring components (Java 22+) |
History: record patterns were previewed in Java 19 (JEP 405) and Java 20 (JEP 432) and became standard in Java 21 (JEP 440), together with pattern matching for switchfor
Deconstructing with instanceof
The describePoint(4, 4)x == yPoint(3, 7)null
public class Deconstruct {
record Point(int x, int y) {
}
record Line(Point start, Point end) {
}
static String describe(Object obj) {
// Test the type and pull out the components in one step
if (obj instanceof Point(int x, int y) && x == y) {
return "point on the diagonal at " + x;
}
if (obj instanceof Point(var x, var y)) { // var infers int
return "point " + x + "," + y;
}
// Nested patterns reach into components of components
if (obj instanceof Line(Point(var x1, var y1), Point(var x2, var y2))) {
double length = Math.hypot(x2 - x1, y2 - y1);
return "line of length " + length;
}
return "not a shape: " + obj;
}
public static void main(String[] args) {
System.out.println(describe(new Point(4, 4)));
System.out.println(describe(new Point(3, 7)));
System.out.println(describe(new Line(new Point(0, 0), new Point(3, 4))));
System.out.println(describe("hello"));
System.out.println(describe(null));
}
}
Output:
point on the diagonal at 4
point 3,7
line of length 5.0
not a shape: hello
not a shape: null
- The bound variables can be used in the rest of the
condition, as in&& , because they are definitely assigned when the pattern has matched.x == y in a pattern takes the component's declared type, herevar .int- The
pattern contains twoLine patterns, so four coordinates come out of two levels of records in one expression, andPoint gives 5.0.Math.hypot(3, 4) reaches the last line safely: no pattern matchesdescribe(null) , so nonull is thrown.NullPointerException
Record patterns in switch
When the selector type is a sealed interface whose permitted subclasses are all records, a switchdefault
public class SwitchOnRecords {
sealed interface Shape permits Circle, Rect, Triangle {
}
record Circle(double radius) implements Shape {
}
record Rect(double width, double height) implements Shape {
}
record Triangle(double base, double height) implements Shape {
}
static double area(Shape s) {
// No default branch: the compiler knows these three cases cover every Shape
return switch (s) {
case Circle(double r) -> Math.PI * r * r;
case Rect(double w, double h) -> w * h;
case Triangle(double b, double h) -> 0.5 * b * h;
};
}
static String classify(Shape s) {
return switch (s) {
case Rect(double w, double h) when w == h -> "square " + w;
case Rect(double w, double h) -> "rectangle " + w + " x " + h;
case Circle c when c.radius() == 0 -> "point-sized circle";
case Circle c -> "circle r=" + c.radius();
case Triangle t -> "triangle";
};
}
public static void main(String[] args) {
Shape[] shapes = {new Circle(1), new Rect(2, 3), new Rect(2, 2), new Triangle(4, 5),
new Circle(0)};
for (Shape s : shapes) {
System.out.printf("%-22s area %6.3f%n", classify(s), area(s));
}
}
}
Output:
circle r=1.0 area 3.142
rectangle 2.0 x 3.0 area 6.000
square 2.0 area 4.000
triangle area 10.000
point-sized circle area 0.000
printed "square 2.0" because the guarded caseRect(2, 2) comes first. Placed after the unguardedwhen w == h case, it could never be reached, and the compiler rejects that order as dominated (shown running further down).Rect- The circle of radius 1 has area 3.142, which is π rounded to three places, and the triangle 0.5 × 4 × 5 = 10.
uses only record patterns.area mixes them with type patterns such asclassify ; use whichever reads better per case.Circle c- If the selector itself is
, the switch throwsnull unless it has aNullPointerException label.case null
Nested patterns on a tree: simplifying expressions
Nested patterns are at their best on recursive data. The program models arithmetic expressions as a sealed interface with four records, then writes evaluation, printing and simplification as switches. The three test expressions each trigger a different simplification rule: multiply by 1, double negation, and multiply by 0.
public class Expressions {
sealed interface Expr permits Num, Add, Mul, Neg {
}
record Num(int value) implements Expr {
}
record Add(Expr left, Expr right) implements Expr {
}
record Mul(Expr left, Expr right) implements Expr {
}
record Neg(Expr inner) implements Expr {
}
static int eval(Expr e) {
return switch (e) {
case Num(int v) -> v;
case Add(Expr l, Expr r) -> eval(l) + eval(r);
case Mul(Expr l, Expr r) -> eval(l) * eval(r);
case Neg(Expr inner) -> -eval(inner);
};
}
// Nested patterns describe the shape of the tree that a rule applies to
static Expr simplify(Expr e) {
return switch (e) {
case Add(Num(int a), Num(int b)) -> new Num(a + b);
case Add(Expr l, Num(int z)) when z == 0 -> simplify(l);
case Mul(Expr l, Num(int one)) when one == 1 -> simplify(l);
case Mul(Expr l, Num(int z)) when z == 0 -> new Num(0);
case Neg(Neg(Expr inner)) -> simplify(inner);
case Add(Expr l, Expr r) -> new Add(simplify(l), simplify(r));
case Mul(Expr l, Expr r) -> new Mul(simplify(l), simplify(r));
case Neg(Expr inner) -> new Neg(simplify(inner));
case Num n -> n;
};
}
static String show(Expr e) {
return switch (e) {
case Num(int v) -> Integer.toString(v);
case Add(Expr l, Expr r) -> "(" + show(l) + " + " + show(r) + ")";
case Mul(Expr l, Expr r) -> show(l) + " * " + show(r);
case Neg(Expr inner) -> "-" + show(inner);
};
}
public static void main(String[] args) {
Expr x = new Mul(new Add(new Num(2), new Num(3)), new Num(1));
Expr y = new Neg(new Neg(new Add(new Num(7), new Num(0))));
Expr z = new Mul(new Add(new Num(4), new Num(5)), new Num(0));
for (Expr e : new Expr[] {x, y, z}) {
Expr s = simplify(e);
System.out.printf("%-14s = %3d simplified: %-6s = %d%n",
show(e), eval(e), show(s), eval(s));
}
}
}
Output:
(2 + 3) * 1 = 5 simplified: 5 = 5
--(7 + 0) = 7 simplified: 7 = 7
(4 + 5) * 0 = 0 simplified: 0 = 0
- Each rule in
is the shape of the tree it applies to.simplify reads exactly like "a negation of a negation". The same check written withcase Neg(Neg(Expr inner)) and casts would take four lines per rule.instanceof became 5 in two steps: the(2 + 3) * 1 rule dropped the multiplication, and the recursive call foldedMul(..., Num(1)) intoAdd(Num(2), Num(3)) .Num(5) lost both negations and the--(7 + 0) , and+ 0 became 0 without evaluating the sum. In every case(4 + 5) * 0 gives the same result before and after, which is the test that a simplifier is correct.eval- Patterns are tried top to bottom. The specific rules come before the general
case, which simplifies both sides and rebuilds the node.Add(Expr l, Expr r) - This is the job the visitor pattern used to do. Adding a new operation is now one new method with a switch, and adding a new record makes every non-exhaustive switch fail to compile.
Generic records and type tests on components
With a generic record such as Box<T>case Box(String s)Stringwhen i > 100null
public class GenericRecords {
record Box<T>(T value) {
}
record Pair<A, B>(A first, B second) {
}
static String unwrap(Box<?> box) {
// A nested type pattern tests the component's runtime type
return switch (box) {
case Box(String s) -> "string of length " + s.length();
case Box(Integer i) when i > 100 -> "big integer " + i;
case Box(Integer i) -> "integer " + i;
case Box(Box(var inner)) -> "box inside a box holding " + inner;
case Box(var other) -> "something else: " + other;
};
}
public static void main(String[] args) {
System.out.println(unwrap(new Box<>("hello")));
System.out.println(unwrap(new Box<>(7)));
System.out.println(unwrap(new Box<>(500)));
System.out.println(unwrap(new Box<>(new Box<>(3.5))));
System.out.println(unwrap(new Box<>(null)));
// Type arguments are inferred: no casts needed for first and second
Pair<String, Integer> p = new Pair<>("age", 42);
if (p instanceof Pair(var key, var value)) {
System.out.println(key.toUpperCase() + " = " + (value + 1));
}
}
}
Output:
string of length 5
integer 7
big integer 500
box inside a box holding 3.5
something else: null
AGE = 43
- The
value skippednull andBox(String s) , because a narrower type test never matchesBox(Integer i) . It was caught bynull , sinceBox(var other) covers the whole component type.var - That last case is also what makes the switch exhaustive. Without it, the compiler rejects the switch, because a box holding a
at the top level would match no case.Double - For
the compiler infersPair(var key, var value) andString from the static typeInteger , soPair<String, Integer> andtoUpperCase() work without casts and printvalue + 1 .AGE = 43
Accessor calls, null components and MatchException
The matching steps described at the top have visible consequences. The program overrides one accessor so it prints when called and another so it divides by zero, and builds a line whose end point is null
public class AccessorCalls {
record Temp(double celsius) {
@Override
public double celsius() {
System.out.println(" celsius() called");
return celsius;
}
}
record Ratio(int num, int den) {
@Override
public int num() {
return num / den; // throws when den is 0
}
}
record Line(Temp start, Temp end) {
}
public static void main(String[] args) {
Object t = new Temp(21.5);
System.out.println("type pattern:");
if (t instanceof Temp temp) {
System.out.println(" matched " + temp);
}
System.out.println("record pattern:");
if (t instanceof Temp(double c)) {
System.out.println(" matched, c = " + c);
}
Object bad = new Ratio(1, 0);
try {
String s = switch (bad) {
case Ratio(int n, int d) -> "ratio " + n + "/" + d;
default -> "other";
};
System.out.println(s);
} catch (MatchException e) {
System.out.println("switch: MatchException caused by " + e.getCause());
}
try {
if (bad instanceof Ratio(int n, int d)) {
System.out.println("ratio " + n + "/" + d);
}
} catch (MatchException e) {
System.out.println("instanceof: MatchException caused by " + e.getCause());
}
// A null component: a record pattern does not match it, a type pattern does
Object line = new Line(new Temp(10), null);
System.out.println("Line(Temp(var a), Temp(var b)) matches: "
+ (line instanceof Line(Temp(var a), Temp(var b))));
if (line instanceof Line(Temp(var a), Temp end)) {
System.out.println("Line(Temp(var a), Temp end) matches, end = " + end);
}
}
}
Output:
type pattern:
matched Temp[celsius=21.5]
record pattern:
celsius() called
matched, c = 21.5
switch: MatchException caused by java.lang.ArithmeticException: / by zero
instanceof: MatchException caused by java.lang.ArithmeticException: / by zero
Line(Temp(var a), Temp(var b)) matches: false
celsius() called
Line(Temp(var a), Temp end) matches, end = null
- The type pattern
printed nothing extra, but the record patternTemp temp calledTemp(double c) . Unlike the generatedcelsius() , which reads fields directly, a record pattern always goes through the accessor.equals - When the accessor threw
, both theArithmeticException and theswitch threwinstanceof with the original exception as the cause. CatchingMatchException around a pattern would not work; the real error is inArithmeticException .getCause() did not match, because the nested record patternLine(Temp(var a), Temp(var b)) rejects theTemp(var b) end. Notice that no "celsius() called" line appears before it: the compiled code rejected thenull end before reading the start's temperature, so accessors are not necessarily called in source order. Keep accessors free of side effects, and do not depend on when or how often they run.null did match, withLine(Temp(var a), Temp end) . A type pattern that covers the component's declared type is unconditional, so it matchesend = null ; inside a record pattern that means a bound variable can benull .null
Exhaustiveness and dominance, checked by the compiler
The compiler proves that a switch over records covers every possible value, including combinations of nested components. The program compiles five switches over a Pairjavax.toolsjavac
import java.net.URI;
import java.util.List;
import java.util.Locale;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
// Compiles small switches in memory and prints what javac says about each one
public class PatternRules {
static final String TYPES = """
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
record Pair(Shape a, Shape b) {}
""";
public static void main(String[] args) {
check("all four combinations of a pair", """
case Pair(Circle a, Circle b) -> 1;
case Pair(Circle a, Square b) -> 2;
case Pair(Square a, Circle b) -> 3;
case Pair(Square a, Square b) -> 4;
""");
check("one combination missing", """
case Pair(Circle a, Circle b) -> 1;
case Pair(Circle a, Square b) -> 2;
case Pair(Square a, Circle b) -> 3;
""");
check("first component by type, second as any Shape", """
case Pair(Circle a, Shape b) -> 1;
case Pair(Square a, Shape b) -> 2;
""");
check("unguarded case before a guarded one", """
case Pair(Circle a, Shape b) -> 1;
case Pair(Circle a, Shape b) when a.r() > 1 -> 2;
case Pair(Square a, Shape b) -> 3;
""");
check("wrong number of components", """
case Pair(Circle a) -> 1;
default -> 0;
""");
}
static void check(String label, String cases) {
String source = TYPES + "class T { int f(Pair p) { return switch (p) {\n"
+ cases + "}; } }";
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
JavaFileObject file = new SimpleJavaFileObject(
URI.create("string:///T.java"), JavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return source;
}
};
boolean ok = javac.getTask(null, null, diags,
List.of("-d", System.getProperty("java.io.tmpdir")), null, List.of(file)).call();
System.out.println(label + ":");
if (ok) {
System.out.println(" compiles");
}
for (Diagnostic<? extends JavaFileObject> d : diags.getDiagnostics()) {
String text = d.getMessage(Locale.ENGLISH).strip();
System.out.println(" error: " + String.join(" ", text.split("\\s*\\n\\s*")));
}
}
}
Output:
all four combinations of a pair:
compiles
one combination missing:
error: the switch expression does not cover all possible input values
first component by type, second as any Shape:
compiles
unguarded case before a guarded one:
error: this case label is dominated by a preceding case label
wrong number of components:
error: incorrect number of nested patterns required: Shape,Shape found: Circle
- A pair of two shapes has 2 × 2 = 4 combinations. Listing all four compiles without
; leaving outdefault fails with "does not cover all possible input values".Pair(Square, Square) - Two cases are enough when the second component is the whole type
: the compiler sees thatShape andCircle in the first position cover the sealed interface.Square - An unguarded case followed by the same pattern with a guard is rejected as "dominated", because the second could never run. Put guarded cases first.
- A record pattern must list every component.
fails with "incorrect number of nested patterns"; usePair(Circle a) or, in Java 22 and later,var for the ones you do not need._
Choosing between patterns, accessors and visitors
| Situation | Use |
|---|---|
| You already have a variable of the record type and need one value | The accessor, p.x() |
An Object | instanceof Point(var x, var y) |
| Different handling per record type in a sealed hierarchy | Exhaustive switchdefault |
| Rules that depend on the shape of nested data | Nested record patterns, specific cases first |
| Conditions on component values | when |
| Components you do not use (Java 22+) | The unnamed pattern _ |
| Hierarchy that is not sealed, or classes that are not records | Type patterns, or the classic visitor pattern |
Related pages: