Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Language Features by Version

Unnamed variables and patterns

Reference for Java's unnamed variables and patterns: where the underscore is allowed, how it works in catch, lambdas, for loops and record patterns.

An unnamed variable is a variable you must declare but do not intend to use. Since Java 22 you write it as a single underscore, _. It tells the reader and the compiler "this value is deliberately ignored", and it removes the need to invent throwaway names such as ignored or unused.

The same idea works in patterns: an unnamed pattern _ matches anything without binding it, and var _ or Type _ matches and discards. Unnamed variables and patterns were previewed in Java 21 and became final in Java 22, so they run on Java 25 without any flags.

Java
catch (NumberFormatException _) { ... }
for (var _ : items) { count++; }
if (shape instanceof Rect(double w, _)) { ... }

Try it

Java Where the underscore is allowed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Unnamed patterns in a switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Where _ is allowed

Position Example
Local variable declaration var _ = compute();
Resource in try-with-resources try (var _ = lock.acquire())
Basic for init for (int i = 0, _ = sideEffect(); i < 3; i++)
Enhanced for variable for (var _ : items)
catch parameter catch (IOException _)
Lambda parameter (_, value) -> value
Type pattern case Circle _ ->
Record component pattern Point(int x, _)
Unnamed pattern Point(_, _)

Usage notes

  • _ is not a normal name: you cannot read it, assign to it later or pass it on. System.out.println(_) is a compile error.
  • You can declare any number of _ variables in the same scope; they do not clash.
  • It is not allowed for method parameters, fields, method names or class names. A method must name its parameters.
  • Before Java 9 _ was a valid identifier (with a warning); from Java 9 to 21 it was an error.
  • In a case with several patterns (case A _, B _), no pattern may bind a variable, so unnamed patterns are what make multi-type cases possible.
  • Prefer Point(int x, _) over Point(int x, int ignored); it tells readers the second component truly does not matter. A nested record pattern like Point(_, _) still requires the component itself to be a Point (and not null).
  • Use _ sparingly. If you find yourself ignoring most of a record, a plain accessor call is often clearer.