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

Before Java 21, reading the values out of an Object that might be a Point took three steps: an instanceof test, a cast, and accessor calls. A record pattern does them in one: obj instanceof Point(int x, int y) is true only when obj is a Point, and then x and y hold its components. This is called deconstruction, the reverse of the constructor.

Matching a value v against Point(int x, int y) happens in this order:

  1. If v is null, the pattern does not match. A record pattern never matches null.
  2. If v is not a Point, it does not match.
  3. Otherwise the JVM calls the accessor for each component, v.x() and v.y(), and matches each result against the nested pattern (int x, int y). A nested pattern can itself be a record pattern, which is how patterns reach several levels into a structure.

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 MatchException. And a nested pattern that is a plain type covering the whole component type, such as var b or Shape b, matches null components, while a nested record pattern does not.

The forms a record pattern can take
FormExampleMatches a null component?Best for
Explicit typesPoint(int x, int y)Primitives cannot be nullReadability when types are short
varPoint(var x, var y)YesLong or generic component types
Nested record patternLine(Point(var a, var b), var end)No, for the nested partTree and message structures
Narrower type testBox(String s) on Box<Object>NoDispatching on a component's runtime type
Guarded casecase Rect(var w, var h) when w == hSame as the patternConditions on the values
Unnamed patternPoint(var x, _)YesIgnoring 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 switch (JEP 441). The Java 20 preview also allowed record patterns in the header of an enhanced for loop; that was removed in the final version. Each example below is a full program whose output was produced on JDK 21.

Deconstructing with instanceof

The describe method tries patterns in order, and each input reaches a different branch: Point(4, 4) passes the x == y condition, Point(3, 7) fails it, the line from (0,0) to (3,4) has a whole-number length of 5, and a string and null match nothing.

Java
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:

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 x == y, because they are definitely assigned when the pattern has matched.
  • var in a pattern takes the component's declared type, here int.
  • The Line pattern contains two Point patterns, so four coordinates come out of two levels of records in one expression, and Math.hypot(3, 4) gives 5.0.
  • describe(null) reaches the last line safely: no pattern matches null, so no NullPointerException is thrown.

Record patterns in switch

When the selector type is a sealed interface whose permitted subclasses are all records, a switch that covers every record is exhaustive, and the compiler accepts it without a default. If someone adds a fourth shape, every such switch stops compiling until it is handled. The test shapes include a square and a zero-radius circle so that both guards fire.

Java
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:

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
  • Rect(2, 2) printed "square 2.0" because the guarded case when w == h comes first. Placed after the unguarded Rect case, it could never be reached, and the compiler rejects that order as dominated (shown running further down).
  • The circle of radius 1 has area 3.142, which is π rounded to three places, and the triangle 0.5 × 4 × 5 = 10.
  • area uses only record patterns. classify mixes them with type patterns such as Circle c; use whichever reads better per case.
  • If the selector itself is null, the switch throws NullPointerException unless it has a case null label.

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.

Java
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:

Output
(2 + 3) * 1    =   5   simplified: 5      = 5
--(7 + 0)      =   7   simplified: 7      = 7
(4 + 5) * 0    =   0   simplified: 0      = 0
  • Each rule in simplify is the shape of the tree it applies to. case Neg(Neg(Expr inner)) reads exactly like "a negation of a negation". The same check written with instanceof and casts would take four lines per rule.
  • (2 + 3) * 1 became 5 in two steps: the Mul(..., Num(1)) rule dropped the multiplication, and the recursive call folded Add(Num(2), Num(3)) into Num(5).
  • --(7 + 0) lost both negations and the + 0, and (4 + 5) * 0 became 0 without evaluating the sum. In every case eval gives the same result before and after, which is the test that a simplifier is correct.
  • Patterns are tried top to bottom. The specific rules come before the general Add(Expr l, Expr r) case, which simplifies both sides and rebuilds the node.
  • 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>, the type written inside the pattern becomes a test on the component: case Box(String s) matches only a box whose value really is a String. The inputs cover a string, a small and a large integer for the when i > 100 guard, a box inside a box, and a box holding null.

Java
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:

Output
string of length 5
integer 7
big integer 500
box inside a box holding 3.5
something else: null
AGE = 43
  • The null value skipped Box(String s) and Box(Integer i), because a narrower type test never matches null. It was caught by Box(var other), since var covers the whole component type.
  • That last case is also what makes the switch exhaustive. Without it, the compiler rejects the switch, because a box holding a Double at the top level would match no case.
  • For Pair(var key, var value) the compiler infers String and Integer from the static type Pair<String, Integer>, so toUpperCase() and value + 1 work without casts and print 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.

Java
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:

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 Temp temp printed nothing extra, but the record pattern Temp(double c) called celsius(). Unlike the generated equals, which reads fields directly, a record pattern always goes through the accessor.
  • When the accessor threw ArithmeticException, both the switch and the instanceof threw MatchException with the original exception as the cause. Catching ArithmeticException around a pattern would not work; the real error is in getCause().
  • Line(Temp(var a), Temp(var b)) did not match, because the nested record pattern Temp(var b) rejects the null end. Notice that no "celsius() called" line appears before it: the compiled code rejected the null 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.
  • Line(Temp(var a), Temp end) did match, with end = null. A type pattern that covers the component's declared type is unconditional, so it matches null; inside a record pattern that means a bound variable can be 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 Pair of two sealed shapes in memory with the javax.tools API and prints what javac says, so the rules are seen running rather than stated.

Java
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:

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 default; leaving out Pair(Square, Square) fails with "does not cover all possible input values".
  • Two cases are enough when the second component is the whole type Shape: the compiler sees that Circle and Square in the first position cover the sealed interface.
  • 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. Pair(Circle a) fails with "incorrect number of nested patterns"; use var or, in Java 22 and later, _ for the ones you do not need.

Choosing between patterns, accessors and visitors

When to use which
SituationUse
You already have a variable of the record type and need one valueThe accessor, p.x()
An Object or interface value might be a record, and you need its componentsinstanceof Point(var x, var y)
Different handling per record type in a sealed hierarchyExhaustive switch with record patterns, no default
Rules that depend on the shape of nested dataNested record patterns, specific cases first
Conditions on component valueswhen guards
Components you do not use (Java 22+)The unnamed pattern _
Hierarchy that is not sealed, or classes that are not recordsType patterns, or the classic visitor pattern

Related pages: records, sealed types with pattern matching, pattern matching for switch and unnamed patterns and variables.