Sub topic 3
Declaring an unnamed variable with _
This chapter assumes you know Java local variables, methods, and basic loops. It uses Java 22 or later, where unnamed variables are a standard feature (JEP 456). No preview flag is needed.
What an unnamed variable is
An unnamed variable is a variable you declare with the single underscore _ as its name. You use it when the language requires a declaration but your code never reads the value.
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
class Drain {
public static void main(String[] args) {
Queue<String> queue = new ArrayDeque<>(List.of("a", "b", "c"));
String _ = queue.remove();
String _ = queue.remove();
String last = queue.remove();
System.out.println(last);
}
}This program prints c. The first two calls to remove() are made for their side effect of taking an element off the queue. The returned values are discarded, and _ tells the reader that this is intentional.
Rules that follow from "no name"
A variable with no name cannot be referred to. This leads to three rules:
- You cannot read an unnamed variable. Writing
System.out.println(_)is a compile-time error. - You can declare
_many times in the same scope, as the example above does. Each declaration is a separate variable, so they never clash. - You can still choose a type.
String _andvar _are both valid, and the initializer is still evaluated.
The last rule matters because the initializer keeps running. String _ = queue.remove(); changes the queue exactly as String s = queue.remove(); would. Only the name is gone.
Why this is better than a throwaway name
Before Java 22 you would write something like String ignored = queue.remove();. This works, but it has costs:
- Readers must scan the rest of the method to check whether
ignoredis used. - Static analysis tools and IDEs may warn about an unused variable.
- Names such as
ignored,unused, anddummydiffer from project to project.
An unnamed variable makes the intent part of the language. The compiler enforces it: if the variable could be read, you would have given it a name.
Where it is allowed
The _ name is accepted in several declaration positions. The table lists them and points to the chapters that cover each in detail.
| Position | Example | Covered |
|---|---|---|
| Local variable | `var _ = compute();` | Next chapter |
| Enhanced `for` variable | `for (var _ : items)` | Next chapter |
| `try-with-resources` resource | `try (var _ = open())` | Next chapter |
| `catch` parameter | `catch (Exception _)` | Two chapters on |
| Lambda parameter | `_ -> 0` | Two chapters on |
| Pattern variable | `case Circle _` | Later chapters |
The diagram shows the decision you make when you write a declaration.
Common mistakes
Most errors come from treating _ as a normal name.
- Reading it. Code such as
int _ = 5; int y = _ + 1;does not compile. If you need the value, name the variable. - Using it where no variable is declared.
_is not a general placeholder expression. You cannot writefoo(_)as a way of saying "any argument". It only works in the declaration positions listed above. - Running on an older JDK. In Java 8 an underscore identifier produced a warning. From Java 9 to 20 it was an error. In Java 21 it was available only as a preview feature. On those versions, code using
_as shown here will not compile without the right flags, or at all. - Hiding a needed name. If a reader would benefit from knowing what the discarded value was, a name such as
removedHeadcan be clearer than_. A later chapter covers this decision.
A second example with `var`
You can let the compiler infer the type with var. This is useful when the initializer's type is long or obvious from the call.
import java.util.ArrayList;
import java.util.List;
class Counter {
static int sizeAfterSideEffects() {
List<String> log = new ArrayList<>();
var _ = log.add("start");
var _ = log.add("finish");
return log.size();
}
public static void main(String[] args) {
System.out.println(sizeAfterSideEffects());
}
}List.add returns a boolean, which we do not need, so both results go to unnamed variables. The program prints 2. Calling log.add("start"); as a plain statement would also be legal, since Java lets you discard a method result. Use an unnamed variable when you want the declaration form, for example when you are in a context like a loop header that requires a variable.
Exercise
Will this compile on Java 22, and what does it print? int _ = 1; int _ = 2; System.out.println("done");
Show answer
It compiles and prints done. Each _ declares a separate unnamed variable, so declaring _ twice in the same scope does not clash. Neither variable can be read, which is fine because the code never reads them.
Exercise
Why does String _ = queue.remove(); still change the queue, even though the variable has no name?
Show answer
Only the name is dropped. The initializer expression queue.remove() is still evaluated, so its side effect happens. The returned value is simply not kept anywhere you can reach.