Sub topic 3
Declaring an unnamed variable with _
This chapter assumes you can write Java methods, loops, and try/catch blocks. It also assumes you know what a lambda expression is. All code targets Java 22 or later. In Java 22 the feature is final (JEP 456), so no preview flag is needed.
Earlier chapters covered why unused variables cause friction and how the underscore went from legal identifier to compile error. This chapter covers the language rule itself: what an unnamed variable is, where you can declare one, and what it does and does not do.
What an unnamed variable is
An unnamed variable is a variable declaration whose name is the single underscore character, _. It is a real declaration. The compiler checks its type, and the initializer runs. The difference is that the variable has no name, so no later code can read it or assign to it.
You write one when the language requires a declaration but you have no use for the value.
import java.util.concurrent.atomic.AtomicInteger;
public class UnnamedLocals {
private static final AtomicInteger calls = new AtomicInteger();
static int register(String name) {
calls.incrementAndGet();
System.out.println("registered " + name);
return calls.get();
}
public static void main(String[] args) {
int _ = register("alpha");
var _ = register("beta");
int total = register("gamma");
System.out.println("last id = " + total);
System.out.println("calls = " + calls.get());
}
}Running this prints:
registered alpha
registered beta
registered gamma
last id = 3
calls = 3Three points to notice:
- The calls on the first two
registerlines still happen. An unnamed variable never skips its initializer. - Two
_declarations sit in the same block. In Java 21 you would have needed two distinct names such asignored1andignored2. Unnamed variables do not clash because none of them enters the scope. totalis an ordinary named variable and works as before.
The rules that define the feature
An unnamed variable follows a small set of rules. Most compile errors you will see come from breaking one of them.
- It has no name to refer to. After
int _ = 5;you cannot write_ + 1,print(_), or_ = 6. The underscore is only valid in a declaration position. - It needs a type or
var. Writeint _,String _, orvar _. A bare_ = 5;is not a declaration. - A local variable needs an initializer.
int _;is rejected. Since you could never assign to the variable later, a declaration without a value would be pointless. - You can declare as many as you like in one scope. Each
_is independent, so repeating it is not a redeclaration error. - It never shadows anything. Because it has no name, it cannot hide a field or an outer local.
- Type rules are unchanged.
int _ = "text";fails exactly asint x = "text";fails. varinference is unchanged.var _ = register("a");infersint.var _ = null;fails becausenullhas no inferable type, as it does for anyvar.
Here is how the compiler treats common forms:
| Declaration | Result | Reason |
|---|---|---|
| `int _ = compute();` | Compiles | Typed unnamed local with initializer |
| `var _ = compute();` | Compiles | Type inferred from the initializer |
| `int _;` | Compile error | A local needs an initializer |
| `var _ = null;` | Compile error | `var` cannot infer a type from `null` |
| `_ = 5;` | Compile error | No type, and `_` is not a name you can assign to |
| `print(_);` | Compile error | `_` cannot be used as an expression |
| `int _ = 1; int _ = 2;` | Compiles | Unnamed variables do not conflict |
Why the initializer still runs
A common misreading is that _ means "throw this away and skip the work". It does not. The right-hand side is evaluated in full, including any method calls, exceptions, and side effects. Only the storing and later reading are given up.
public class StillRuns {
static int risky() {
throw new IllegalStateException("boom");
}
public static void main(String[] args) {
try {
var _ = risky();
System.out.println("not reached");
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
}
}
}This prints caught: boom. The unnamed variable does not suppress the exception. If you want to avoid the call, delete the line.
When you actually need one
For a plain local variable, the case is narrower than you might expect. If the right-hand side is a method call or an increment, an expression statement already discards the value:
queue.poll(); // legal, result discardedYou do not need var _ = queue.poll(); here. Writing it adds a signal: the result is deliberately ignored. Some static analysis tools and IDE inspections warn about discarded results of certain methods, such as File.delete() or a collection's add result. An unnamed variable tells readers and tools that the discard is intentional.
The feature matters most where a declaration is syntactically required and no expression statement can replace it. The Topic Spine for this tutorial covers those places in the next chapters. For orientation, here are the contexts where an unnamed variable is allowed:
- A local variable declaration in a block, with an initializer.
- A resource in a
try-with-resources statement. - The header of a basic
forstatement. - The loop variable of an enhanced
forstatement. - An exception parameter in a
catchclause. - A formal parameter of a lambda expression.
- A pattern variable in a type pattern, covered later in the pattern chapters.
The following diagram shows how to decide whether _ fits a declaration.
Naming a variable `_` versus other underscore names
Only the single character _ is special. Names such as __, _x, and x_ are still ordinary identifiers. They are legal, they enter the scope, and two of them in the same scope clash.
public class NotSpecial {
public static void main(String[] args) {
int __ = 1; // ordinary identifier, two underscores
int _count = 2; // ordinary identifier
// int __ = 3; // would be a duplicate variable error
System.out.println(__ + _count);
}
}This prints 3. A lone _ is the one spelling that now means "no name here".
A single _ also cannot be used as the name of anything else. Fields, methods, classes, packages, and type parameters called _ are all errors, and so are method and constructor parameters. These restrictions are covered in the chapter on where _ is not allowed. The point for now is that _ is not a general-purpose identifier. It is a marker that is accepted in a fixed list of declaration positions.
Effects on scope, capture, and final
Since an unnamed variable is not in scope, several usual local-variable concerns disappear:
- No capture. A lambda or inner class cannot capture it, because there is nothing to refer to. The "effectively final" rule never applies.
- No definite assignment tracking. You cannot read it, so the compiler has nothing to check.
- No shadowing and no redeclaration errors. You can repeat
_freely.
One more consequence involves tooling. An unused named local normally triggers a compiler lint or an IDE warning. An unnamed variable is excluded from "unused variable" reports because the unused state is the stated intent.
Migrating a named placeholder
Code written before Java 22 often contains names like ignored, unused, or dummy. You can usually replace them mechanically.
Before:
import java.util.List;
public class Before {
static void run(List<String> items) {
int ignored1 = items.size();
int ignored2 = items.size();
System.out.println("checked");
}
}After:
import java.util.List;
public class After {
static void run(List<String> items) {
int _ = items.size();
int _ = items.size();
System.out.println("checked");
}
}Both compile on Java 22, and both print checked when run is called. The second version no longer carries two names that the reader has to confirm are unused.
Before making the replacement, check that the name is really never read. If any later line uses ignored1, replacing it with _ produces a compile error on that line, which is a useful safety net. The compiler will tell you exactly which uses remain.
Common mistakes
- Expecting
_to skip evaluation. The initializer always runs, as shown earlier. - Declaring without a value.
int _;fails. Provide an initializer or remove the variable. - Trying to read it back. Any use of
_outside a declaration is an error. If you find yourself wanting the value, give it a name. - Targeting an older Java release. On Java 8
_produces a warning, and from Java 9 through Java 20 it is an error. Java 21 accepts it only as a preview feature. Check your--releaseormaven.compiler.releasesetting if the compiler rejects_. - Overusing it. A named variable such as
elapseddocuments what a value means even if the code does not read it. Use_when the value truly carries no meaning for the reader.
Summary of this chapter's rules
An unnamed variable is a declaration written with _ in place of a name. It is type-checked, its initializer runs, and it never enters scope, so it cannot be read, captured, or shadow anything. You can repeat it freely in one scope. It is accepted only in specific declaration positions, and a local one needs an initializer. The next chapters apply the same idea to loops, try-with-resources, catch parameters, lambdas, and finally to patterns.
Exercise
Which of these lines compile on Java 22? Explain each failure. (a) var _ = Math.random(); (b) int _; (c) var _ = null; (d) String _ = "x"; String _ = "y"; (e) int __ = 1; int __ = 2;
Show answer
(a) compiles; var infers double and the call runs. (b) fails because a local needs an initializer. (c) fails because var cannot infer a type from null. (d) compiles because unnamed variables do not clash. (e) fails because __ is an ordinary identifier, so the second declaration duplicates the first.
Exercise
The following method prints a line each time touch() is called. How many lines does run() print, and does replacing var _ with touch(); as a plain statement change the output?
static int touch() { System.out.println("touched"); return 1; }
static void run() { var = touch(); var = touch(); }
Show answer
It prints "touched" twice, because each initializer runs even though the value is discarded. Replacing each declaration with the plain statement touch(); gives the same output. The unnamed variable only documents that the returned value is deliberately ignored.
Exercise
A teammate's code compiles on their machine with Java 22 but fails on your build server with an error about _ being an invalid identifier. Name two likely causes and a fix.
Show answer
The build server may be using a JDK older than 22, or the build may set a --release or source level below 22. In either case the compiler treats _ as a reserved name and rejects it. Fix it by upgrading the JDK and setting the release level to 22 or higher, or by reverting the code to named placeholder variables.