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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
