skip to content

What do Java's unnamed variables and patterns let you write, and how do `_`, `var _` and a named variable you never read differ?

level: middleimportance: should knowfreq 42%

answer

  1. a slot you need, no name
  2. a keyword that cannot be read
  3. no discard expression exists
  4. a type before it still tests
  5. bare underscore equals var underscore in patterns

basics

~20 s

The keyword _ declares a local, catch parameter, lambda parameter or pattern variable that has no name and so cannot be read. Alone in a record pattern it matches anything, like var _. A named variable stays readable and can clash.

solid answer

~40 s

Since Java 22, `_` stands in for a name you will not use: a local with an initializer, a `for` or try-with-resources variable, a `catch` parameter, a lambda parameter or a type-pattern variable. Alone inside a record pattern, as in `ColoredPoint(Point(int x, _), _)`, it is the match-all pattern, equivalent to `var _`; both match anything, including `null`. `RedBall _` differs: it still tests the type and only drops the name. A named variable you never read also compiles, but it stays in scope, can be read by mistake, can clash with another name, and is illegal in a `case` with several patterns. `_` is not a discard operator: `_ = f();` does not compile, initializers still run, and record accessors are still called. Fields and method parameters cannot be unnamed.

code

java · 30 lines
java
import java.util.List;
import java.util.function.BiFunction;

public class Unnamed {
    sealed interface Ball permits Red, Blue {}
    record Red() implements Ball {}
    record Blue() implements Ball {}
    record Box(Ball content) {}

    static String describe(Box box) {
        return switch (box) {
            case Box(Red _), Box(Blue _) -> "a ball"; // several patterns, no bindings
            case Box(_) -> "empty";                   // also matches a null component
        };
    }

    public static void main(String[] args) {
        int total = 0;
        for (var _ : List.of("a", "b")) {
            total++;
        }
        try {
            Integer.parseInt("x");
        } catch (NumberFormatException _) {
            total = -total;
        }
        BiFunction<String, String, Integer> zero = (_, _) -> 0;
        System.out.println(total + " " + zero.apply("a", "b") + " " + describe(new Box(null)));
    }
}

go deeper

for a junior

Recall where underscore replaces a name: catch parameters, lambda parameters, locals and patterns. Know that it cannot be read afterwards, and that fields and method parameters are excluded.

for a middle

Explain the two roles: an unnamed variable drops only the name and keeps any type test, while bare underscore in a record pattern matches everything, exactly like var underscore, including a null component.

for a senior

Use it to make intent enforceable in review: merged case labels, unused catch parameters and try-with-resources contexts. Know it saves no work, because initializers and record accessors still run and a throwing accessor still surfaces.

for a principal

Decide what a team's style guide says: replace unused names on sight or only in new code, how static-analysis rules should treat them, and whether the supported baseline allows Java 22 syntax yet.

## What the feature is **Unnamed variables and patterns** let a declaration say that it needs a slot but not a name for it. They previewed in Java 21 (JEP 443) and became final in Java 22 (JEP 456). `_` is a keyword (JLS 3.9), and an entity declared with it cannot be referred to by name (JLS 6.1). It plays two roles: - an **unnamed variable** replaces only the name, as in `int _`, `var _` or `Point _`; - the **match-all pattern** is `_` alone inside a record pattern, and it replaces both the type and the name. ## Where `_` is allowed | Place | Example | Note | |---|---|---| | Local variable statement | `var _ = queue.remove();` | Initializer required | | Basic `for` header | `for (int i = 0, _ = setUp(); i < 10; i++)` | Initializer required | | Enhanced `for` header | `for (var _ : orders) total++;` | | | try-with-resources | `try (var _ = context.acquire()) { }` | Initializer required | | `catch` parameter | `catch (NumberFormatException _)` | Multi-catch works too | | Lambda parameter | `_ -> "NODATA"`, `(_, _) -> 0`, `(String _, int _) -> 0` | Several in one lambda are fine | | Type pattern | `case Red _ ->`, `o instanceof Point _` | Top level or nested | | Record sub-pattern | `o instanceof ColoredPoint(_, Color c)` | Nested only | Fields, method and constructor parameters, record components, and the names of classes and methods cannot be `_`. JEP 456 lists unnamed fields and method parameters as a non-goal. Three small rules follow from having no name: - `System.out.println(_)` is rejected, because there is nothing to read; - `int _;` is rejected, because the value could never be set later; - `int _[] = ...` is rejected, because `_` takes no brackets. Several unnamed variables can share a block, since none of them has a name to clash. ## `_`, `var _` and a type, inside a record pattern Given `record Box(Ball content)`, where `Red` is a subtype of `Ball`: | Pattern | Tests the component's type | Matches a `null` component | Declares a usable variable | |---|---|---|---| | `Box(Red r)` | Yes | No | Yes | | `Box(Red _)` | Yes | No | No | | `Box(Ball _)` | Unconditional for `Ball` | Yes | No | | `Box(var _)` | No | Yes | No | | `Box(_)` | No | Yes | No | JLS 14.30.1 says the match-all pattern is equivalent to a nested type pattern that declares an unnamed pattern variable with `var`, so the last two rows are one behaviour with two spellings. As patterns, both exist only directly inside a record pattern: `o instanceof _`, `case _ ->` and `o instanceof var _` are all rejected, and in a `switch` the top-level catch-all is `default` or `case Object _ ->`. A null `Box` itself matches no record pattern. Outside patterns the spellings separate. A local needs a type or `var`, so `var _ = f();` compiles and `_ = f();` does not. A lambda parameter accepts all three forms: `_`, `var _` and `String _`. ## What a named variable you never read does differently - **It stays usable.** It remains in scope, so later code can read it by accident and a maintainer has to check that nothing does. `_` makes non-use a fact the compiler enforces. - **It can clash.** A `catch` or lambda parameter cannot reuse the name of a local in scope. `_` never clashes. - **It blocks merged labels.** JLS 14.11.1 rejects a `case` label that has more than one pattern and declares a pattern variable outside its guard. `case Box(Red _), Box(Blue _) ->` compiles, and `case Integer i, Boolean _ ->` does not. - **Tools see it differently.** `javac -Xlint:all` says nothing about an unused named local, but JEP 456 notes that static analysis tools typically complain about one. `_` states the intent. ## What `_` does not do - **It is not a discard expression.** Nothing lets you assign to `_`. Write `var _ = f();` or simply `f();`. - **It does not skip work.** The initializer of `var _ = queue.remove();` still runs. JLS 14.30.2 determines each record component by invoking its accessor, so an accessor that throws still produces a `MatchException` under `_`. - **It does not touch other underscores.** `_age`, `MAX_AGE`, `__` and `1_000` keep their old meaning. ## How `_` got here 1. Java 8 warned about `_` as an identifier. 2. Java 9 made that an error (JEP 213), which freed the token. 3. Java 21 previewed the feature (JEP 443). 4. Java 22 finalized it without change (JEP 456), and Java 25 and 27 behave the same.

  • Why is `case Integer i, Boolean _ ->` rejected when only one of its patterns declares a name?
    JLS 14.11.1 forbids a `case` label with more than one pattern from declaring pattern variables outside its guard. If the value were a `Boolean`, `i` would be uninitialized in the body, so the compiler cannot let the body use it. Making every pattern unnamed, as in `case Integer _, Boolean _ ->`, compiles.
  • Does `Box(_)` match a `Box` whose component is `null`, and does `Box(Red _)`?
    `Box(_)` does: every value matches a match-all pattern, `null` included. `Box(Red _)` does not, because `Red _` is not unconditional for a component of type `Ball`, so it is not null-matching. A `null` reference to the `Box` itself matches neither, because `null` never matches a record pattern.
  • Does replacing a record component with `_` avoid calling its accessor?
    No. JLS 14.30.2 determines each record component by invoking its accessor, and `javac` on Java 25 and 27 generates the call for `_` as well. An accessor that throws therefore still makes the match fail with a `MatchException` whose cause is the original exception, so `_` is about clarity, not speed.
  • Why can't method parameters be unnamed when lambda parameters can?
    JEP 456 makes it a non-goal. Its Alternatives section says unnamed method parameters interact subtly with the specification and tooling, such as what overriding means for them and how Javadoc would describe them, and leaves that to a possible future JEP. A lambda parameter has no visibility outside its method, so renaming it has no external impact.

  • _ = compute(); is a valid way to discard a result.
  • An unnamed variable can still be read as _ in the next statement.
  • Box(Red _) matches any Box because the underscore ignores the component.
  • Using _ in a record pattern skips the accessor call, so it is a performance optimization.
  • Fields and method parameters can be declared with _ as well.
  • Box(_) and Box(var _) match different values.

Unnamed variables and patterns
Java 22pre-release 21
Record patterns
Java 21pre-release 19

Assumes Java 27; unnamed variables and patterns previewed in 21 and are final since 22, and Java 25 compiles and behaves the same.

context