Java 21: Nested record patterns

Record patterns nest, letting you destructure composed data in one step.

Code
record Point(int x, int y) {}
record Line(Point from, Point to) {}

Object o = new Line(new Point(0, 0), new Point(3, 4));
if (o instanceof Line(Point(var x1, var y1), Point(var x2, var y2))) {
    double len = Math.hypot(x2 - x1, y2 - y1);
    System.out.println("length = " + len);
}
Output
length = 5.0
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26