Skip to main content

Unnamed variables and patterns

Definition​

An underscore _ (Java 22) marks a variable you must declare but will never use, such as a loop variable, a caught exception or a part of a pattern. It tells the reader, and the compiler, that the value is ignored on purpose.

Example code​

Underscore for values you do not need

import java.util.List;

record Point(int x, int y) { }

class Demo {
public static void main(String[] args) {
int count = 0;
for (var _ : List.of("a", "b", "c")) { // the element itself is not needed
count++;
}
System.out.println(count);

try {
Integer.parseInt("abc");
} catch (NumberFormatException _) { // the exception object is not needed
System.out.println("not a number");
}

Object obj = new Point(3, 9);
if (obj instanceof Point(int x, _)) { // only x matters
System.out.println("x = " + x);
}
}
}

// Output:
// 3
// not a number
// x = 3

Finished this page? Track your progress (saved only in your browser).