Records and pattern matching

A record pattern tests an object against a record type and, in the same expression, takes the object apart into its components. It is the record form of the pattern variable of lesson 059, and it is final in Java 21. The two places it appears are instanceof and switch.

A record in instanceof

value instanceof Point(int x, int y) is true only when the value is a Point, and then the two components are bound to x and y for the rest of the branch. There is no cast and no accessor call:

public class InstanceofDemo { public static void main(String[] args) { Object[] values = {new Point(1, 2), "text", new Point(3, 4)}; for (Object value : values) { if (value instanceof Point(int x, int y)) { System.out.println("point " + x + " " + y + " sum " + (x + y)); } else { System.out.println("not a point: " + value); } } } } record Point(int x, int y) { }

javac -Xlint:all InstanceofDemo.java
java InstanceofDemo

point 1 2 sum 3
not a point: text
point 3 4 sum 7

The middle value is a String, the pattern does not match, and its branch is skipped: x and y do not exist there. The same test written the old way needs a cast after the check, and the cast is a line that can be wrong; the pattern makes the check and the cast one thing.

What deconstruction is

A record is the only type Java deconstructs, because its components are its state and the compiler knows them. The pattern Point(int x, int y) asks three questions at once: is the value a Point, and what are its two components, which must themselves be assignable to the pattern types. That is why a record pattern reads as the record's declaration: it mirrors the component list.

The component patterns need not be plain variables. They may be type patterns or other record patterns, which is the next section, and they may be var, which infers the component type.

Records in a switch

The same pattern is a case of a switch, and over a sealed interface the switch is exhaustive without a default. The shape hierarchy of the next lessons appears here for the first time:

public class SwitchDemo { public static void main(String[] args) { Shape[] shapes = {new Circle(2.0), new Square(3.0)}; for (Shape shape : shapes) { System.out.println(describe(shape)); } } static String describe(Shape shape) { return switch (shape) { case Circle(double radius) -> String.format("circle r=%.1f", radius); case Square(double side) -> String.format("square s=%.1f", side); }; } } sealed interface Shape permits Circle, Square { } record Circle(double radius) implements Shape { } record Square(double side) implements Shape { }

javac -Xlint:all SwitchDemo.java
java SwitchDemo

circle r=2.0
square s=3.0

Two cases and no default, and the compiler accepts that because Shape is sealed and the two records are the only implementations. Add a third record without a case and the switch stops compiling; lesson 060 shows that error in full, and lesson 058 the keyword.

Nested record patterns

A record that holds records is deconstructed in one pattern, level by level. The line below has two points, and the pattern names the four numbers:

public class NestedDemo { public static void main(String[] args) { Line line = new Line(new Point(0, 0), new Point(3, 4)); System.out.println(length(line)); System.out.println(line); } static double length(Line line) { if (line instanceof Line(Point(int x1, int y1), Point(int x2, int y2))) { int dx = x2 - x1; int dy = y2 - y1; return Math.sqrt(dx * dx + dy * dy); } return 0; } } record Point(int x, int y) { } record Line(Point from, Point to) { }

javac -Xlint:all NestedDemo.java
java NestedDemo

5.0
Line[from=Point[x=0, y=0], to=Point[x=3, y=4]]

The three-four-five triangle gives 5.0, and the second line is the generated toString of the record inside the record: the compiler's five members exist at every level.

Guards

A guard is a when clause after a pattern, and it refines the case with a condition on the bound variables:

public class GuardDemo { public static void main(String[] args) { System.out.println(label(new Point(0, 5))); System.out.println(label(new Point(5, 5))); System.out.println(label(new Point(2, 3))); } static String label(Point point) { return switch (point) { case Point(int x, int y) when x == 0 && y != 0 -> "on the y axis"; case Point(int x, int y) when x == y -> "on the diagonal"; case Point(int x, int y) -> "elsewhere at " + x + "," + y; }; } } record Point(int x, int y) { }

javac -Xlint:all GuardDemo.java
java GuardDemo

on the y axis
on the diagonal
elsewhere at 2,3

The cases are tried in order and the first match wins, so the guard that accepts a point on the axis must come before the plain one that accepts everything. A switch over a record with guards is not exhaustive by itself: the last case here has no guard and covers the rest, and without it the compiler would refuse the switch.

The rules

A record pattern names the type and a component pattern per component, in the declared order; the wrong number of components is a compile error. The bound variables exist only where the pattern matched. Patterns are tried in order, so a broader pattern before a narrower one makes the narrower one unreachable, which the compiler reports. A guard may read only the variables of its own pattern.

Deconstruction needs a record, not any class: a class with getters has no component list for the compiler to follow. A record whose component is an array can be deconstructed too, and the array is bound as it is, without a copy.

Exercises

  1. Add a String to the array of InstanceofDemo and predict which branch it takes before you run it.
  2. Give Line a method that answers whether it is horizontal, using a record pattern.
  3. Add a guard that labels a point on the x axis and check the order of the cases.
  4. Deconstruct a Line into two var components and print each point's class.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which types can a record pattern deconstruct?

    Answer

    Records, because their components are their state

    The compiler needs the declared component list, which only a record has.

  2. Where may the variables of a record pattern be read?

    Answer

    Only where the pattern matched

    The bindings exist in the branch whose test succeeded, like a pattern variable.

  3. Why can a switch over a sealed interface omit the default?

    Answer

    The permitted subtypes are known, so the cases can cover all of them

    Exhaustiveness is decided from the sealed hierarchy, and a missing subtype is a compile error.

  4. What does this program print? public class Q1 { public static void main(String[] args) { Object o = new P(2, 3); if (o instanceof P(int a, int b)) { System.out.println(a * b); } } } record P(int a, int b) { }

    Answer

    6

    The pattern binds the two components and the branch multiplies them.

  5. What does this program print? public class Q2 { public static void main(String[] args) { Object o = "text"; System.out.println(o instanceof P(int a)); } } record P(int a) { }

    Answer

    false

    The value is not a P, so the pattern does not match and the expression is false.

  6. What does this program print? public class Q3 { public static void main(String[] args) { System.out.println(area(new C(2))); } static int area(Object o) { return switch (o) { case C(int r) -> r * r; default -> 0; }; } } record C(int r) { }

    Answer

    4

    The record pattern binds r to 2 and the case computes its square.

  7. What does this program print? public class Q4 { public static void main(String[] args) { System.out.println(text(new P(0, 4))); System.out.println(text(new P(1, 4))); } static String text(P p) { return switch (p) { case P(int x, int y) when x == 0 -> "axis"; case P(int x, int y) -> "off axis " + y; }; } } record P(int x, int y) { }

    Answer

    axis then off axis 4

    The guard accepts only the first point, and the second falls to the unguarded case.

  8. What does this program print? public class Q5 { public static void main(String[] args) { Line line = new Line(new P(1, 2), new P(3, 4)); if (line instanceof Line(P(int a, int b), P(int c, int d))) { System.out.println(a + b + c + d); } } } record P(int x, int y) { } record Line(P from, P to) { }

    Answer

    10

    The nested pattern binds all four components, and their sum is ten.

  9. What does a guard (when) do in a switch case?

    Answer

    Adds a condition that must hold for the case to be chosen

    The pattern is tested first, then the guard, and only then is the case chosen.

  10. What happens when a record pattern names the wrong number of components?

    Answer

    The compiler reports an error at the pattern

    The pattern must mirror the record declaration, and the compiler checks the count.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev