00:00

Record Patterns in Java 21

Last updated: · Standard (Java 21)

A record pattern tests whether a value is a record and extracts its components in the same step, for example o instanceof Point(int x, int y). Record patterns were previewed in Java 19 and 20 and became standard in Java 21 (JEP 440).

This tutorial covers record patterns in instanceof and switch, nesting, and the rules for types and null.

1. Why Are Record Patterns Useful?

Type patterns (Java 16) removed casts, but you still had to call accessors one by one to reach the data, often several levels deep. Records describe their structure in the header, so the language can use that structure directly: a record pattern deconstructs the value, and nested patterns reach into components that are records themselves.

2. Syntax

Syntax.java
if (o instanceof Point(int x, int y)) { ... }                // explicit component types
if (o instanceof Point(var x, var y)) { ... }                // inferred types
if (o instanceof Line(Point(var x1, var y1), Point p2)) { ... } // nested pattern

switch (shape) {
    case Circle(Point c, double r) when r == 0 -> ...        // with a guard
    case Circle(var c, var r) -> ...
}

3. Practical Examples

Example 1: Deconstructing nested records with instanceof

RecordDeconstruction.java
public class RecordDeconstruction {
    record Money(long amount, String currency) { }
    record LineItem(String product, int qty, Money unitPrice) { }

    static String describe(Object o) {
        // Before: test, cast, then call accessors
        //   if (o instanceof LineItem li) { Money m = li.unitPrice(); ... }

        // Java 21: test and take the record apart in one pattern, including nested records
        if (o instanceof LineItem(String product, int qty, Money(long amount, String cur))) {
            return qty + " x " + product + " = " + (qty * amount) + " " + cur;
        }
        return "not a line item";
    }

    public static void main(String[] args) {
        System.out.println(describe(new LineItem("notebook", 3, new Money(60, "INR"))));
        System.out.println(describe(new LineItem("cable", 2, new Money(4, "USD"))));
        System.out.println(describe("plain text"));
    }
}
Output
3 x notebook = 180 INR
2 x cable = 8 USD
not a line item

Example 2: Record patterns in an exhaustive switch

Combined with a sealed interface, the switch covers every shape without a default, and nested patterns pull out coordinates directly.

PatternsInSwitch.java
public class PatternsInSwitch {
    sealed interface Shape permits Circle, Rect, Line { }
    record Point(double x, double y) { }
    record Circle(Point center, double r) implements Shape { }
    record Rect(Point topLeft, Point bottomRight) implements Shape { }
    record Line(Point from, Point to) implements Shape { }

    static String info(Shape s) {
        return switch (s) {
            case Circle(Point(var x, var y), var r) when r == 0 -> "dot at (" + x + ", " + y + ")";
            case Circle(var center, var r) -> String.format("circle area %.2f", Math.PI * r * r);
            case Rect(Point(var x1, var y1), Point(var x2, var y2)) -> "rect area " + Math.abs((x2 - x1) * (y2 - y1));
            case Line(var a, var b) -> String.format("line length %.2f", Math.hypot(b.x() - a.x(), b.y() - a.y()));
        };
    }

    public static void main(String[] args) {
        System.out.println(info(new Circle(new Point(1, 1), 0)));
        System.out.println(info(new Circle(new Point(0, 0), 2)));
        System.out.println(info(new Rect(new Point(0, 0), new Point(4, 3))));
        System.out.println(info(new Line(new Point(0, 0), new Point(3, 4))));
    }
}
Output
dot at (1.0, 1.0)
circle area 12.57
rect area 12.0
line length 5.00

4. How a Record Pattern Matches

Matching a nested record pattern The value is first tested against the record type, then each component accessor is called and matched against its sub-pattern; the whole pattern matches only if every sub-pattern matches. value Object o type test is it a LineItem? components product, qty, unitPrice nested match Money(amount, cur)
Figure 1: Each level of nesting is one more type test plus accessor calls.

5. Important Points and Best Practices

  • A record pattern never matches null.
  • Use var for components when the type is obvious; use explicit types to narrow, for example Box(String s).
  • The number of sub-patterns must match the number of record components.
  • Since Java 22, unnamed patterns (_) let you ignore components you do not need.
  • Very deep nesting hurts readability; extract a helper method when patterns grow long.

6. Summary

  • Record patterns became standard in Java 21 (JEP 440).
  • They test a record type and extract its components in one step.
  • Patterns can be nested and used in instanceof and switch.
  • With sealed types, switches over record patterns can be exhaustive.

Related Tutorials

7. References