Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Record Patterns: Destructuring and Matching

Learn how Java record patterns destructure records in pattern matching, including nested patterns, switch integration, and common pitfalls.

~5 min readJava
#record patterns#pattern matching#Java 21#switch expressions
Diagram showing a record being destructured into its components using a pattern matching arrow.

Java record patterns, introduced as a preview in Java 19 and finalized in Java 21, let you destructure a record directly in pattern matching. Instead of extracting components manually, you can bind them to variables in a single expression.

What Are Record Patterns?

Record patterns let you match a record type and bind its components to variables in one step. Before Java 21, extracting components from a record required explicit accessor calls. With record patterns, you can write:

java
record Point(int x, int y) {} Object obj = new Point(3, 4); if (obj instanceof Point(int x, int y)) { System.out.println(x + ", " + y); }

The instanceof pattern binds x and y to the record's components. This works because the record's canonical constructor and accessor methods are implied. The pattern syntax mirrors the record declaration.

Basic Syntax and Compile-Time Checks

A record pattern uses the record's type name followed by a parenthesized list of patterns for each component. For example, Point(int x, int y) is a record pattern that matches any Point instance and binds its x and y components.

The compiler verifies that the number of patterns matches the record's component count. If you write Point(int x) for a two-component record, you get a compile error. The component patterns can themselves be patterns—type patterns, nested record patterns, or var patterns—not just variable names. This is where record patterns become powerful.

Nested Record Patterns

Record patterns can be nested inside other record patterns. Consider a Line record that contains two Point instances:

java
record Line(Point start, Point end) {}

You can match a Line and extract the coordinates of both points in one expression:

java
if (obj instanceof Line(Point(int x1, int y1), Point(int x2, int y2))) { // x1, y1, x2, y2 are now in scope }

This eliminates the need for multiple instanceof checks or temporary variables. The pattern matching engine handles the nested destructuring automatically. The syntax is straightforward: each component pattern can itself be a record pattern.

Type Patterns and Null Handling

Record patterns build on type patterns. A type pattern like String s matches any non-null value of type String and binds it to s. A record pattern also tests the outer value with a type pattern, then destructures the record. The outer value must be non-null. If obj is null, the instanceof check fails and the pattern does not match.

This is important because record patterns do not handle null records. If you need to treat null as a valid case—for example, in a switch—you must include a null case explicitly. The compiler enforces exhaustiveness for switch expressions, but null handling is separate. A record with a null component is a different situation, covered in Common Pitfalls below.

Using Record Patterns with Switch

Record patterns integrate with both switch statements and switch expressions. This is where they shine for polymorphic dispatch. Consider a sealed interface Shape with implementations Circle and Rectangle:

java
sealed interface Shape permits Circle, Rectangle {} record Circle(double radius) implements Shape {} record Rectangle(double width, double height) implements Shape {} double area(Shape shape) { return switch (shape) { case Circle(double r) -> Math.PI * r * r; case Rectangle(double w, double h) -> w * h; }; }

The switch expression uses record patterns to destructure each shape directly. Because Shape is sealed, the compiler knows all possible subtypes, so the switch is exhaustive without a default branch. This reduces boilerplate and makes the intent clear.

Guards for Conditional Logic

Sometimes a record pattern alone is not enough; you may also need to test a condition on the bound variables. In switch labels, a when clause adds a boolean guard to a pattern. For example:

java
String describe(Point point) { return switch (point) { case null -> "null"; case Point(int x, int y) when x > 0 && y > 0 -> "first quadrant"; default -> "not in the first quadrant"; }; }

The guard is evaluated only after the pattern matches. If the guard is false, the case is not selected and the next case is tried. In an ordinary if, use && instead:

java
if (obj instanceof Point(int x, int y) && x > 0 && y > 0) { // Only matches points in the first quadrant }

Performance and Runtime Cost

Record patterns are compiled rather than interpreted. The generated code performs type checks and casts, then invokes the record's accessor methods to extract components. There is no reflection involved, so the runtime cost is comparable to manual extraction. The JIT compiler can often inline these accessors, making the overhead negligible.

One subtlety: the order of evaluation in nested patterns is left-to-right. If a component pattern fails to match, the remaining components are not evaluated. This is consistent with short-circuit behavior and can be useful when a later component pattern has side effects—though you should avoid side effects in patterns anyway.

Compatibility and Migration

Record patterns require Java 21 or later. If you are on an earlier version, you can use the preview features in Java 19 and 20, but the syntax was refined. When migrating, note that the when clause replaced the earlier && syntax for guarded patterns. Code written for preview versions may need adjustment.

Also, record patterns work with any record, including local records and records defined inside methods. However, they do not work with classes that are not records. If you have a class with accessor methods, you cannot use record patterns directly; you would need to convert it to a record or use traditional type patterns.

Common Pitfalls and Limitations

One common mistake is assuming that record patterns can bind to fields of a non-record class. They cannot. Another is forgetting that pattern variables are only in scope when the pattern matches. In an if statement, the variables are available in the true branch, not in the else branch.

Another limitation: record patterns cannot be used in a standalone assignment. They only appear in instanceof or switch contexts. You cannot write Point(int x, int y) = point; to destructure outside of pattern matching.

Finally, be clear about null checks on record components. The outer record pattern checks that the record instance is non-null. What happens to a null component depends on the component pattern. If you use a var component pattern, a null component is bound to the pattern variable. For example, given record LabeledPoint(String label, int x, int y) {}, LabeledPoint(var label, var x, var y) matches new LabeledPoint(null, 3, 4) and binds label to null. If you use an explicit reference type pattern, such as LabeledPoint(String label, int x, int y), the nested type pattern follows the usual rule that type patterns do not match null, so the record pattern does not match when label is null. Choose the pattern form that expresses whether null components are allowed, and add a when guard or && condition when you need to enforce a non-null requirement on a var binding.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.