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.
More Related questions...