Java / Java 21 Interview Questions
What are Record Patterns in Java 21 and how do they enable deconstruction?
JEP 440 finalises record patterns, which extend the type-test pattern (instanceof Point p) to simultaneously match a record's type and destructure its components into named variables. This eliminates the boilerplate of calling accessor methods after a type check.
record Point(int x, int y) {}
record Line(Point start, Point end) {}
// Before Java 21: type check + manual accessor calls
if (obj instanceof Point p) {
System.out.println(p.x() + ", " + p.y()); // still need accessors
}
// Java 21 record pattern: match + deconstruct in one step
if (obj instanceof Point(int x, int y)) {
System.out.println(x + ", " + y); // x and y bound directly
}
// Nested record patterns — deconstruct a Line into its Points' components
if (shape instanceof Line(Point(int x1, int y1), Point(int x2, int y2))) {
double length = Math.hypot(x2 - x1, y2 - y1);
System.out.println("Length: " + length);
}
// Record patterns in switch
static String describe(Object obj) {
return switch (obj) {
case Point(int x, int y) when x == 0 && y == 0 -> "Origin";
case Point(int x, int y) when x == 0 -> "On Y-axis";
case Point(int x, int y) -> "Point(" + x + "," + y + ")";
case Line(Point s, Point e) -> "Line from " + s + " to " + e;
default -> "Unknown";
};
}
// Unnamed patterns: _ to ignore components you don't need
if (obj instanceof Point(int x, _)) {
System.out.println("x = " + x); // y component ignored
}Record patterns compose with sealed types, switch expressions, and the when guard clause. The unnamed pattern _ (JEP 443, preview in Java 21) lets you discard components you do not need, avoiding the need to name every field.
More Related questions...