Sub topic 4
Unnamed Locals, for Loops, and try-with-resources
What you need before this chapter
This chapter assumes you can read basic Java: local variables, for and enhanced for loops, and methods. You should know that try (...) closes resources automatically when the block ends. You should also know that var lets the compiler infer a local variable's type.
The code runs on Java 22 or later, where unnamed variables are a standard feature (JEP 456). On Java 21 you need --enable-preview and --release 21. On Java 20 and earlier the code does not compile.
The rule in one paragraph
Some declarations force you to write a name for something you never use. An unnamed variable replaces that name with a single underscore, _. The compiler still checks the type and still runs the initializer. It only skips creating a name you could refer to. A reader sees _ and knows the value is deliberately ignored.
Three places are covered here:
- Local variable declarations inside a block.
- The header of a
forloop, basic or enhanced. - The resource list of a
try-with-resources statement.
Catch parameters, lambda parameters and patterns are covered in later chapters.
Unnamed local variables
Sometimes you call a method for its side effect and the return value is of no use. Without _, you either drop the result by calling the method as a statement, or you invent a name nobody reads. The first option is not always possible. The second leaves an unused variable that linters flag.
Here is a case where discarding the result is reasonable. The code keeps every third element of a queue and throws away the next two.
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
public class Triples {
public static void main(String[] args) {
Queue<Integer> queue = new ArrayDeque<>(List.of(1, 2, 3, 4, 5, 6, 7));
while (queue.size() >= 3) {
int first = queue.remove();
int _ = queue.remove();
var _ = queue.remove();
System.out.println("keep " + first);
}
System.out.println("left over: " + queue);
}
}The output is:
keep 1
keep 4
left over: [7]Three points about this code:
remove()still runs. Each_declaration evaluates its initializer, so the queue shrinks as expected. Declaringint _ = queue.remove();is not the same as skipping the call.- You can declare
_many times in one scope. A named variable cannot be declared twice in the same block. Unnamed variables never clash because they have no name to clash on. - Both
int _andvar _are allowed. Withvar, the type is inferred from the initializer as usual.
A local unnamed variable must have an initializer. A declaration like int _; is rejected. The variable could never be read, and with no name it could never be assigned later, so the declaration would be meaningless.
Unnamed variables in a basic for header
A basic for loop has a header with an initialization part. That part can declare more than one variable, and any of them can be unnamed.
public class Setup {
static int calls = 0;
static int sideEffect() {
calls++;
return calls;
}
public static void main(String[] args) {
for (int i = 0, _ = sideEffect(); i < 3; i++) {
System.out.println("i = " + i);
}
System.out.println("calls = " + calls);
}
}The output is:
i = 0
i = 1
i = 2
calls = 1The initializer sideEffect() runs once, when the loop starts. The loop never sees its result. This form is rare, and most code is clearer if the setup call happens before the loop. It is legal, and you may meet it in code that wants the setup tied to the loop's scope.
You cannot use _ as the counter. A loop such as for (int _ = 0; _ < 3; _++) fails to compile because the condition and the update both read _. A counter exists to be read and updated, so it needs a name. If you want to repeat something three times and never use the index, name the counter anyway, or use IntStream.range(0, 3).forEach(...), where a lambda parameter can be unnamed.
Unnamed variables in an enhanced for loop
The enhanced for loop must declare a loop variable, even when the body never uses the element. This is the most common use of _ in loops.
import java.util.List;
class Orders {
static int countOrders(List<String> orders) {
int total = 0;
for (var _ : orders) {
total++;
}
return total;
}
}An explicit type works too:
import java.util.List;
class Names {
static int countNames(List<String> names) {
int total = 0;
for (String _ : names) {
total++;
}
return total;
}
}Both versions work, but for a List you would write orders.size(). The unnamed loop variable pays off with an Iterable that has no size() method:
class Counting {
static int count(Iterable<?> items) {
int total = 0;
for (var _ : items) {
total++;
}
return total;
}
}For Iterable<?>, var _ resolves to a capture of an unknown type. That is fine because nothing reads the variable.
The same rule applies to arrays. for (int _ : numbers) walks the array and ignores each value. The loop still runs once per element, and the iterator or index machinery runs as it always did.
Unnamed resources in try-with-resources
A try-with-resources statement needs a variable for each resource, because the compiler uses it to call close(). Often the program never touches the resource directly. The resource exists to be held for the length of the block. Typical examples are a lock, a transaction scope or a tracing context. The variable name is pure noise.
class Lock implements AutoCloseable {
static Lock acquire() {
System.out.println("acquired");
return new Lock();
}
@Override
public void close() {
System.out.println("released");
}
}
public class Guarded {
public static void main(String[] args) {
try (var _ = Lock.acquire()) {
System.out.println("working");
}
}
}The output is:
acquired
working
releasedThe resource is still closed when the block ends, normally or by exception. Declaring it with _ only removes the name. close() is called on the object that acquire() returned.
With several resources you can use _ more than once:
try (var _ = Lock.acquire(); var _ = Lock.acquire()) {
System.out.println("working");
}Resources close in the reverse order of declaration, as with named resources. Unnamed resources follow the same rule.
A resource you need to read from, such as a BufferedReader or a Connection, must keep its name. try (var _ = Files.newBufferedReader(path)) opens the file and closes it but gives the body nothing to read.
What the compiler enforces
The rules are small and strict.
| Code | Result | Reason |
|---|---|---|
| `int _ = compute();` | Compiles | Initializer runs, no name created |
| `int _;` | Error | An unnamed local needs an initializer |
| `System.out.println(_);` | Error | `_` is not a name, so it cannot be read |
| `_ = 5;` as an assignment | Error | There is nothing to assign to |
| `int _ = 1; int _ = 2;` in one block | Compiles | No name, so no duplicate |
| `for (int _ = 0; _ < 3; _++)` | Error | The condition and update read `_` |
| `for (var _ : items) { }` | Compiles | The loop variable is never read |
| `try (var _ = open()) { }` | Compiles | The resource is still closed |
Two further rules matter when you move code between versions:
- Before Java 9,
_was a legal identifier, with a warning from Java 8. In Java 9 through 21 it was a compile error. A project that compiles with--release 8can still use_as an ordinary name. Code that uses_as an unnamed variable needs--release 22or later. - Unnamed variables are permitted only in the contexts the language lists. Fields and method parameters are not among them, and a later chapter covers those limits. If you try one, the error message points at the
_.
Choosing between `_` and a name
The diagram shows the decision for the three places in this chapter.
Some guidelines:
- Use
_when the language demands a variable and you have no use for it. Enhancedforandtry-with-resources are the clearest cases. - Prefer a plain statement when one exists.
queue.remove();says the same thing asint _ = queue.remove();, with less text. The declaration form earns its place when it documents that you are deliberately skipping a value, as in the triples example. - Do not hide a value you might need. If a later change could use the element, a descriptive name is easier to extend than a
_that you must rename. - Do not use
_to silence a warning about an unused variable you should have deleted. If the whole statement has no purpose, remove it.
Common mistakes
- Treating
_as a discard operator. It is a declaration, not an expression. You cannot writefoo(_)orx = _. - Expecting the initializer to be skipped. Side effects always happen, including exceptions the initializer throws.
- Assuming
_makes a loop faster. The iteration is identical. Only the name is gone. - Mixing up the two uses of the word "unnamed". In this chapter
_appears in a declaration. In pattern matching, a separate unnamed pattern exists, and a later chapter explains how it differs. - Compiling with an old
--release. The error appears on the line with_, but the fix is a compiler setting, not the code.
Exercises
Exercise
What does try (var _ = Lock.acquire(); var _ = Lock.acquire()) { System.out.println("working"); } print, using the Lock class from this chapter, and why is it legal to declare _ twice?
Show answer
It prints "acquired", "acquired", "working", "released", "released", one per line. Both resources are opened in order, the body runs, and both are closed in reverse order (the two close messages look identical). Declaring _ twice is legal because an unnamed variable has no name, so there is nothing to clash with.
Exercise
Which of these fail to compile on Java 22: (a) int _; (b) for (int _ = 0; _ < 3; _++) { } (c) var _ = List.of(); (d) for (String _ : names) { }, assuming names is a List<String>?
Show answer
(a) and (b) fail. (a) has no initializer, and an unnamed local needs one. (b) reads and increments _ in the condition and update, but _ is not a name and cannot be read or assigned. (c) compiles, with var inferring List<Object>. (d) compiles, because the loop variable is never read.
Exercise
You have String line = reader.readLine(); and never use line because you only want to skip a header row. Name two ways to write this without an unused named variable, and say which you prefer.
Show answer
Write the call as a plain statement, reader.readLine();, or declare var _ = reader.readLine();. The plain statement is shorter and is preferred here. The var _ form is better only if you want the declaration to document that a value is being skipped on purpose, for example alongside other unnamed declarations in a block.