Why is this an issue?

The syntax of some Java constructs, such as enhanced for loops, requires that you declare a variable that you may have no use for. To solve this issue, Java 22 introduced an unnamed variable pattern, _. This feature removes the need to name variables that are syntactically required but otherwise unused. Moreover, it clearly indicates the intent not to use the variable.

To further minimize clutter, unnamed variables should use the var pattern rather than explicit type declarations. In addition to minimizing clutter, removing the type makes the code easier to maintain. Indeed, if the type was to change in future, the code would remain the same.

Exceptions

This rule does not apply to basic for loops and local variable declarations in a block.

How to fix it

Replace the local variable type with var.

Code examples

Noncompliant code example

for (String _ : myIterable) { // Noncompliant
  // ...
}


try (Resource _ = new Resource()) { // Noncompliant
  // ...
}

Compliant solution

for (var _ : myIterable) {
  // ....
}

try (var _ = new Resource()) {
  // ...
}

Resources

Documentation