Sub topic 4
Unnamed Locals, for Loops, and try-with-resources
This chapter assumes you know Java local variables, the enhanced for loop, try-with-resources, and basic exceptions. It uses Java 22 or later, where unnamed variables (JEP 456) are a standard feature.
The working model
An unnamed variable is a declaration whose name is _. The variable is still declared, so it has a type and it is initialized. But it has no name, so no code can read or write it afterward.
You use it when the language forces you to declare a variable and you have no use for the value. Three common places are local variable declarations, enhanced for loops, and try-with-resources resources.
Unnamed local variables
A local variable declaration with an initializer can use _ as its name. This is useful when the right-hand side has a side effect you want, but the result does not matter.
import java.util.ArrayDeque;
import java.util.Queue;
class Drain {
static int drain(Queue<String> queue) {
int removed = 0;
while (queue.size() > 2) {
var _ = queue.poll();
removed++;
}
return removed;
}
public static void main(String[] args) {
Queue<String> q = new ArrayDeque<>(java.util.List.of("a", "b", "c", "d"));
System.out.println(drain(q));
}
}The call to poll() removes an element. We discard the element, and var _ tells the reader that this is deliberate. The program prints 2.
A local declaration with _ must have an initializer. int _; is an error, because there would be no way to ever give the variable a value.
You can declare _ more than once in the same scope. Each declaration is a separate variable, and none of them can clash with another.
class TwoIgnored {
static void run() {
var _ = Integer.parseInt("1");
var _ = Integer.parseInt("2");
System.out.println("both parsed");
}
}Unnamed variables in for loops
The enhanced for loop requires a loop variable, even when you only want to repeat something once per element. Use _ to say that the element is not needed.
import java.util.List;
class Orders {
static int countOrders(List<String> orders) {
int total = 0;
for (var _ : orders) {
total++;
}
return total;
}
}The same idea applies to the init part of a basic for statement. In this form you declare a variable you never read again.
class Repeat {
static void sideEffects(java.util.Iterator<String> it) {
for (var _ = it.next(); it.hasNext(); ) {
System.out.println(it.next());
}
}
}This skips the first element and prints the rest. It is legal, but a plain call to it.next(); before the loop reads more clearly. Reach for _ in a basic for only when the declaration really belongs in the loop header.
Unnamed resources in try-with-resources
A try-with-resources statement declares a resource so that Java closes it for you. Sometimes the resource matters only because it is open, for example a lock or a scoped timer. You never refer to it in the body, so you can leave it unnamed.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Guarded {
private final Lock lock = new ReentrantLock();
// A small wrapper so that releasing the lock is an AutoCloseable action.
private AutoCloseable acquire() {
lock.lock();
return lock::unlock;
}
int compute() throws Exception {
try (var _ = acquire()) {
return 42;
}
}
}The resource is still closed when the block ends. Only its name is gone. Because AutoCloseable.close() declares throws Exception, the method must handle or declare that exception.
Common errors
| Mistake | Result |
|---|---|
| `int _;` with no initializer | Compile error: a local `_` needs an initializer |
| Reading `_` as in `System.out.println(_)` | Compile error: `_` is not a usable name |
| Using `_` as a field name | Compile error: only local-style declarations may be unnamed |
| Compiling with Java 8 or older source level | `_` is rejected as a keyword-like token |
Exercise
What is wrong with this loop, and how do you fix it? for (String _ : names) { count++; } compiles, but a teammate asks why int _; on its own line does not. Explain the difference.
Show answer
The loop is valid. The enhanced for supplies the value of each element as the initializer, so the unnamed variable is always initialized. The line int _; has no initializer, so the variable could never receive a value and the compiler rejects it. To make it valid, write something like int _ = 0; or var _ = compute();.
Exercise
A method opens a Scanner in a try-with-resources block but only calls System.in-independent code in the body. Rewrite try (Scanner sc = new Scanner("x")) { run(); } so the resource has no name.
Show answer
try (var _ = new Scanner("x")) { run(); }. The Scanner is still closed at the end of the block, but the code no longer declares a name that it never uses.