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.
catch (NumberFormatException _) { ... } for (var _ : items) { count++; } if (shape instanceof Rect(double w, _)) { ... }
Try it
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.
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
casewith 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, _)overPoint(int x, int ignored); it tells readers the second component truly does not matter. A nested record pattern likePoint(_, _)still requires the component itself to be aPoint(and not null). - Use
_sparingly. If you find yourself ignoring most of a record, a plain accessor call is often clearer.