Unnamed variables with _
Code Comparison
try {
parse(input);
} catch (Exception ignored) {
log("parse failed");
}
map.forEach((key, value) -> {
process(value); // key unused
});
try {
parse(input);
} catch (Exception _) {
log("parse failed");
}
map.forEach((_, value) -> {
process(value);
});
Why the modern way wins
๐ข
Clear intent
_ explicitly says 'this value is not needed here'.
๐
No warnings
IDEs and linters won't flag intentionally unused variables.
๐งน
Cleaner lambdas
Multi-param lambdas are cleaner when you only need some params.
Old Approach
Unused Variable
Modern Approach
_ Placeholder
JDK Support
Unnamed variables with _
Available
Finalized in JDK 22 (JEP 456, March 2024).
How it works
Unnamed variables communicate to readers and tools that a value is deliberately ignored. No more 'ignored' or 'unused' naming conventions, no more IDE warnings.
Related Documentation
Proof