Unnamed Patterns & Variables
Unnamed Patterns and Variables (JEP 443) is a Preview feature in Java 21 that introduces the underscore (_) as a way to say “I don’t care about this value.”
The Problem: Unused Variables
Have you ever written a loop or a catch block where you had to declare a variable you never intended to use?
try {
int number = Integer.parseInt(input);
} catch (NumberFormatException e) { // 'e' is unused
System.out.println("Invalid number");
}
Or when iterating:
for (Order order : orders) {
total++; // 'order' is unused
}
These unused variables clutter the code and can sometimes trigger compiler warnings or static analysis violations.
The Solution: The Underscore _
In Java 21, you can replace these with _. This clearly signals to the reader (and the compiler): “This variable exists, but I am ignoring it.”
try {
int number = Integer.parseInt(input);
} catch (NumberFormatException _) { // Clean!
System.out.println("Invalid number");
}
Synergy with Record Patterns
This feature shines when combined with Record Patterns. Often, you deconstruct a record but only need one specific field.
Before, you had to declare variables for everything:
// We only want 'x', but we have to declare 'y'
if (obj instanceof Point(int x, int y)) {
System.out.println("X is: " + x);
}
Now, you can use an Unnamed Pattern:
// 'y' is ignored using '_'
if (obj instanceof Point(int x, _)) {
System.out.println("X is: " + x);
}
You can even ignore the type type entirely if strict type inference allows it:
if (obj instanceof Point(int x, var _)) { ... }
Summary
- Readability: Reduces visual noise.
- Intent: Clearly explicitly states that a value is irrelevant.
- Safety: Impossible to accidentally use a variable you meant to ignore.