What are record patterns in Java 21?

Record patterns let you take a record apart in a pattern: instead of matching a record and then calling its accessors, you match its components directly, including nested records. They work in instanceof and in switch, and can be combined with guards.

Key Points: • obj instanceof Point(int x, int y) checks the type and extracts x and y in one step. • Patterns can be nested: case Line(Point(var x1, var y1), Point(var x2, var y2)). • var can be used for components when you don't want to repeat the types. • Combined with sealed interfaces, this gives a concise, type-safe way to process data structures such as expression trees or events. • Java 22 added unnamed patterns (_) for components you don't need.

Code Example:

public class RecordPatternDemo {

    sealed interface Expr permits Num, Add, Mul {}
    record Num(int value) implements Expr {}
    record Add(Expr left, Expr right) implements Expr {}
    record Mul(Expr left, Expr right) 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(Num(int a), Num(int b)) -> a * b;     // nested pattern
            case Mul(Expr l, Expr r) -> eval(l) * eval(r);
        };
    }

    public static void main(String[] args) {
        // (2 + 3) * 4
        Expr expr = new Mul(new Add(new Num(2), new Num(3)), new Num(4));
        System.out.println("Result: " + eval(expr));

        Object obj = new Num(7);
        if (obj instanceof Num(int value) && value > 5) {
            System.out.println("Big number: " + value);
        }
    }
}

Output:

Result: 20 Big number: 7

Good to Know: The expression-evaluator example above is the classic way to show sealed interfaces, records and record patterns working together. It's worth practising, because it shows you understand how the three features were designed to fit together.

Interview Tip: A concise interview answer is:

"Record patterns let me deconstruct a record directly in instanceof or switch, for example case Point(int x, int y), including nested records. Combined with sealed interfaces, they give a concise and type-safe way to process data structures such as an expression tree."

Previous question: What is pattern matching for switch in Java 21?

Next question: What are text blocks in Java?

More Java 17 and 21 Features interview questions

All Java 17 and 21 Features questions