Boost Java Readability with Unnamed Patterns and Variables in Java 21
Java 21 adds a preview feature called Unnamed Patterns and Variables that lets developers replace unused variables with an underscore, simplifying try‑catch blocks, loops and other code structures to improve readability and maintainability.
Java 21 introduces a preview feature called Unnamed Patterns and Variables (in addition to JEP 445) aimed at improving code readability and maintainability.
Traditionally a try‑catch block is written as:
try {
// ...
} catch (Exception e) {
System.out.println("An error has occurred!");
}Here the variable e is often unused.
With the new JEP 443 feature you can replace the unused variable with an underscore:
try {
// ...
} catch (Exception _) {
System.out.println("An error has occurred!");
}In short, any declared variable that you do not intend to use can be replaced by the underscore _, which applies to try‑catch blocks, for‑loops and other scenarios.
Recommended Reading
Java 21 New Feature: Virtual Threads
Java 21 New Feature: Sequenced Collections
Java 21 StringBuilder and StringBuffer repeat method
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
