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.

Programmer DD
Programmer DD
Programmer DD
Boost Java Readability with Unnamed Patterns and Variables in Java 21

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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingcode maintenanceunnamed-patterns
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.