Java / Java 21 Interview Questions
What are Unnamed Patterns and Variables in Java 21 (Preview) and how do they reduce boilerplate?
JEP 443 (preview in Java 21) introduces the underscore _ as a special token meaning 'I don't care about this value'. It can be used as an unnamed variable in catch blocks, try-with-resources, enhanced for loops, and lambda parameters — and as an unnamed pattern component in record patterns.
// --- Unnamed variable in catch ---
// Before: must name the exception even if you don't use it
try { processFile(); } catch (IOException e) { throw new RuntimeException(e); }
// After (Java 21 Preview):
try { processFile(); } catch (IOException _) { throw new RuntimeException("failed"); }
// --- Unnamed variable in enhanced for ---
int count = 0;
for (var _ : list) count++; // iterate just for the count, don't need the element
// --- Unnamed pattern component in record pattern ---
record Point(int x, int y) {}
record Line(Point start, Point end) {}
// Only care about the x of start, ignore everything else
if (shape instanceof Line(Point(int x, _), _)) {
System.out.println("Line starts at x=" + x);
}
// --- Unnamed lambda parameter ---
list.forEach(_ -> count++);
// Multiple unnamed variables in same scope (all named _ — allowed)
try {
int _ = Integer.parseInt(s1);
int _ = Integer.parseInt(s2); // two _ variables, both unnamed
} catch (NumberFormatException _) {
System.out.println("Parse failed");
}Before JEP 443, Java required naming every variable even if it was intentionally unused, leading to suppressed warnings (@SuppressWarnings("unused")) and distracting variable names like ignored or dummy. The underscore communicates intent clearly: this value exists but is deliberately not examined.
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...
