Blog post

Java 22: Leverage unnamed variables and patterns

Jonathan Vila

Jonathan Vila Lopez

Developer Advocate - Java

8 min read

Understanding the new features in Java is crucial for writing updated, efficient, and high quality code. To assist developers in adopting these changes correctly, SonarQube has introduced several new rules designed to check for the proper usage of unnamed variables and patterns, ensuring your code adheres to best practices and avoids common pitfalls.

In this three-part blog series, we’ll be covering the latest features in Java 22, 23, and 24, and the new SonarQube rules to help you effectively take advantage. 

In this first blog, we’re digging into Java 22, which introduces several new language features. But there’s one particularly important — the Unnamed variables and patterns with simple examples.


What are Unnamed variables and patterns?

A significant and welcome addition in Java 22 is the finalization of Unnamed variables and patterns, officially detailed in JEP 456. This feature enhances code clarity by allowing developers to use an underscore (_) for variables and patterns that are intentionally left unused. 

This elegantly addresses common scenarios where a variable is required by syntax but has no relevance to the business logic, such as a caught exception object that is never inspected or a loop variable in an enhanced for-loop where only the iteration count matters. 

By replacing these placeholder names with a simple underscore, developers can reduce code clutter, eliminate "unused variable" warnings, and more clearly express their intent. This ultimately leads to higher-quality, more maintainable Java code.

SonarQube introduces a suite of new rules to ensure proper adoption of Java 22's unnamed variables and patterns. These rules — including S7466, S7467, and S7475 — guide developers in leveraging this feature for more maintainable code. Adhering to these guidelines enables teams to significantly improve code clarity and address redundant warnings.


Rule S7466: Unnamed variable declarations should use the var identifier

When declaring an Unnamed variable, the type declaration often becomes redundant. The primary purpose of an Unnamed variable is to signal that it won't be used, making its specific type less critical. Using var in this context enhances conciseness and maintains focus on the intent: to intentionally ignore the variable.

Let's look at an example. When iterating over a collection where only the number of iterations matters, the element itself is not used.

Noncompliant code example:

int count = 0;

for (String element : myList) { // "element" is unused

    count++;

}

In Java 22, you can use an Unnamed variable. However, explicitly declaring the type is unnecessary.

Noncompliant code example:

int count = 0;

for (String _ : myList) { // The type "String" is redundant

    count++;

}

This is where rule S7466 comes in, suggesting a cleaner, more concise approach.

Compliant solution:

int count = 0;

for (var _ : myList) {

    count++;

}

By using var, the code becomes less verbose and the intent remains clear.


Rule S7467: Unused exception parameters should use the Unnamed variable pattern

A common scenario in Java is catching an exception where the exception object itself is not needed. Previously, developers would have to declare the exception variable, even if it was never referenced, leading to "unused variable" warnings from static analysis tools. Java 22's Unnamed variables provide a perfect solution for this.

Consider a try-catch block where the simple fact that an exception was caught is enough, and its details are irrelevant.

Noncompliant code example:

try {

    // some operation that might throw an exception

} catch (NumberFormatException e) { // "e" is unused

    // log that the format was invalid

}

While functional, the declaration of e is noise. Using an unnamed variable is a better approach, and this is what SonarQube now recommends.

Compliant solution:

try {

    // some operation that might throw an exception

} catch (NumberFormatException _) {

    // log that the format was invalid

}

This compliant solution is cleaner and explicitly communicates that the exception object itself is not important for the handling logic.


Rule S7475: Types of unused record components should be removed from pattern matching

Record patterns, a powerful feature for deconstructing record instances, are also enhanced by unnamed patterns. When pattern matching against a record, you might only be interested in a subset of its components. With Unnamed patterns, you can ignore the components you don't need.

When an entire record component is unused in a pattern match, specifying its type is superfluous. Rule S7475 encourages the removal of these unnecessary type declarations, leading to more readable and less cluttered code.

Imagine you have a ColoredPoint record and you only need the Point component in your logic.

Noncompliant code example:

if (obj instanceof ColoredPoint(Point p, Color c)) { // "c" is unused

    // logic that only uses p

}

In Java 22, you can use an unnamed pattern for the Color component. However, including the type is not necessary if the component is completely ignored.

Noncompliant code example:

if (obj instanceof ColoredPoint(Point p, Color _)) { // The type "Color" is redundant

    // logic that only uses p

}

The most concise and readable version, as enforced by SonarQube, omits the type for the unused component entirely.

Compliant solution:

if (obj instanceof ColoredPoint(Point p, _)) {

    // logic that only uses p

}

This approach makes the code more focused on the relevant data, improving maintainability.

How Java 22 and SonarQube work together

By embracing the new features in Java 22 —such as Unnamed variables and patterns—developers can write more efficient, and more maintainable code resulting in a higher-quality code. However, staying abreast of these evolving language enhancements and consistently applying best practices can be challenging. 

This is where tools like SonarQube, become invaluable. They provide automated checks that help ensure your code not only leverages these modern features correctly, but also adheres to high quality standards, ultimately improving code clarity and overall project quality.

Ready to transform your code?

See how easy it is to integrate SonarQube into your workflow and start finding bugs and vulnerabilities today.

Image for rating

120+ G2 Reviews

Solicitar una demostraciónTry For Free
  • Follow SonarSource on Twitter
  • Follow SonarSource on Linkedin
language switcher
Español (Spanish)
  • Documentación jurídica
  • Centro de confianza

© 2008-2024 SonarSource SA. Todos los derechos reservados. SONAR, SONARSOURCE, SONARQUBE, y CLEAN AS YOU CODE son marcas comerciales de SonarSource SA.