Sub topic 10
Where `_` Is Not Allowed
This chapter assumes you already know the allowed uses of _ from the earlier chapters: unnamed locals, loop variables, catch parameters, lambda parameters, Type _ pattern variables, and the unnamed pattern _ in record patterns. It also assumes you know sealed types, records, and switch patterns. Here you learn the boundaries: where the compiler rejects _, why it does so, and what to write instead.
The rule behind the restrictions
An unnamed variable is a variable that nobody can read. That is only safe where the declaration is private to a small piece of code and no caller, subclass, or other class depends on the name.
Every restriction in this chapter follows from that rule. The compiler allows _ where the name would be invisible anyway. It rejects _ where the name is part of a contract or where a declaration cannot work without a name.
The allowed and rejected positions are:
| Position | `_` allowed? | Reason |
|---|---|---|
| Local variable with an initializer | Yes | The name is local, and the initializer gives it a value. |
| Local variable without an initializer | No | You could never assign it later, so it would never hold a value. |
| Enhanced `for` variable | Yes | The loop supplies each value. |
| Basic `for` initializer | Yes | It is a local declaration with an initializer. |
| `try`-with-resources resource | Yes | The resource is closed automatically. |
| `catch` parameter (including multi-catch) | Yes | The handler may not need the exception. |
| Lambda parameter | Yes | The lambda body may not need the argument. |
| Field (instance or static) | No | Other code reads fields by name. |
| Method or constructor parameter | No | The name documents the API. |
| Record component in the header | No | A component is also a private field and an accessor. |
| Class, method, type parameter, package, or label name | No | These names are referenced from elsewhere. |
| Top-level pattern `_` | No | A top-level `_` would match anything, so it is never a real test. |
| Reading `_` in an expression | No | An unnamed variable has no name to refer to. |
Fields are never unnamed
A field exists so that other code can refer to it. An unnamed field could not be read, assigned, or even referred to, so the compiler rejects it. The same applies to static fields.
class Counter {
// int _ = 0; // error: '_' is not allowed as a field name
// static int _ = 0; // error: same reason
private int count = 0; // a field needs a real name
void increment() {
count++;
}
}If you want a field only for its side effect, it does not need to be a field. Initialize it in a constructor or static initializer block instead.
Method and constructor parameters are never unnamed
Parameter names look private, but they are part of how a method is understood. They appear in Javadoc, in IDE hints, in stack traces under debug info, and in reflection when the code is compiled with -parameters. Subclasses overriding a method also see them.
Java therefore requires a real name even when an implementation ignores the argument.
interface Listener {
void onEvent(String name);
}
class LoggingListener implements Listener {
// public void onEvent(String _) { } // error: parameter of a method
@Override
public void onEvent(String name) {
System.out.println("event received");
}
}An unused method parameter is therefore still a normal parameter. If a compiler or linter warns about it, suppress the warning or document why the parameter exists.
Lambda parameters are the exception, because a lambda is an anonymous implementation of a functional interface. The interface method already defines the contract, so the lambda's own names are private to its body.
import java.util.function.BiFunction;
class LambdaOk {
public static void main(String[] args) {
BiFunction<String, String, Integer> constant = (_, _) -> 42;
System.out.println(constant.apply("a", "b"));
}
}You can use several _ parameters in one lambda, because no name can collide.
Record components in a record header
A record header such as record Point(int x, int y) declares parameters, fields, and accessor methods all at once. Each one needs a name.
// record Pair(int _, int second) {} // error: component must be named
record Pair(int first, int second) {}This is easy to confuse with record patterns, where _ is allowed. A record pattern such as Pair(_, var s) only deconstructs an existing record. The header declares the record itself.
A local variable needs an initializer
For a local variable, _ is allowed only if the declaration includes an initializer. Without one, the variable would stay unassigned forever, because you cannot write _ = 5 afterward.
import java.util.ArrayDeque;
import java.util.Queue;
class LocalRule {
static void drain(Queue<String> queue) {
// int _; // error: no initializer
int _ = queue.size(); // allowed: initializer runs for its effect
var _ = queue.poll(); // allowed: discards the removed element
}
public static void main(String[] args) {
Queue<String> q = new ArrayDeque<>(java.util.List.of("a", "b"));
drain(q);
System.out.println(q);
}
}The initializer still runs. var _ = queue.poll(); removes the head of the queue and throws the result away, which is the point of the feature.
You cannot read or assign `_`
An unnamed variable is not a variable you can refer to. Both of these lines are errors:
class NoRead {
static void demo() {
int _ = 10;
// System.out.println(_); // error: cannot use '_' in an expression
// _ = 20; // error: cannot assign to '_'
}
}If you find yourself wanting to read the value, the variable was never unused. Give it a name.
The top-level `_` pattern is not allowed
Chapter 8 showed _ inside a record pattern, as in Line(Point(int x, _), _). That nested use is the only place the unnamed pattern _ can appear.
You cannot write _ as the entire pattern in instanceof or in a case label:
class TopLevel {
static boolean test(Object o) {
// return o instanceof _; // error: '_' cannot be the whole pattern
return o instanceof Object _; // allowed: unnamed pattern variable
}
static String classify(Object o) {
return switch (o) {
// case _ -> "anything"; // error
case String _ -> "string";
case Object _ -> "other";
};
}
}A bare _ pattern would match everything, including null in some contexts, without stating a type. Java requires a type test at the top level, so write Type _. For a catch-all branch in a switch, use default.
The distinction is:
Type _is an unnamed pattern variable. It tests the type and declares a binding nobody can read. It is allowed at the top level and nested._is the unnamed pattern. It matches anything and tests nothing. It is allowed only nested inside a record pattern.
Multiple patterns in a case need `_` for every binding
You can list several patterns in one case label only when none of them declares a named binding. Otherwise, the body would not know which binding exists.
sealed interface Shape permits Circle, Square, Triangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {}
class Corners {
static String describe(Shape s) {
return switch (s) {
case Circle _ -> "round";
// case Square q, Triangle t -> "has corners"; // error: named bindings
case Square _, Triangle _ -> "has corners"; // allowed
};
}
public static void main(String[] args) {
System.out.println(describe(new Square(2)));
}
}A record pattern can also appear in a multi-pattern label if its bindings are all unnamed, as in case Square(_), Triangle(_, _). If the body needs a value from one of the shapes, split the label into separate cases.
Names that are always real names
Since Java 9, _ alone is not a valid identifier. Java 22 gives it meaning only in the positions above. Everywhere else the compiler rejects it. This includes class, interface, method, and package names, type parameters, labels, and enum constants.
// class _ {} // error
// <_> void f() {} // error: type parameter
// _: for (;;) { break _; } // error: labelCompiler error text varies by version, but it generally says that _ is only allowed to declare unnamed patterns, local variables, exception parameters, or lambda parameters. If you see that message, the position you used is not on the allowed list.
A decision flow
The diagram below summarizes how to decide whether a declaration can use _.
Common errors and fixes
| You wrote | Problem | Fix |
|---|---|---|
| `void run(int _)` | Parameters need names | Name it, for example `ignored`. |
| `int _;` | No initializer | Add one, or remove the variable. |
| `print(_)` | Cannot read `_` | Give the variable a name. |
| `case _ ->` | Bare `_` at top level | Use `default ->` or `Object _ ->`. |
| `case A a, B b ->` | Named bindings in a multi-pattern case | Use `A _, B _` or split into two cases. |
| `record R(int _)` | Record component needs a name | Name it, or omit the component. |
Using `_` safely
Choosing a real name is not a failure. A name such as ignored, unused, or a descriptive one can still help a reader, and it works in every Java version. Use _ where it removes noise: loops that only count, catch blocks that ignore the exception, and patterns that look only at part of a record.
Exercise
Which of these declarations does not compile in Java 22: for (var _ : list) {}, catch (IOException _) {}, void log(String _) {}, or Function<String, Integer> f = _ -> 1;? Explain why.
Show answer
void log(String _) {} does not compile. A method parameter is part of the method's API and must have a real name. The other three are allowed: an enhanced for variable, a catch parameter, and a lambda parameter.
Exercise
Why does o instanceof _ fail while o instanceof Object _ compiles, and what does case Point(_, _) do that a bare case _ cannot?
Show answer
The unnamed pattern _ is allowed only nested inside a record pattern, so a top-level _ is rejected. Object _ is a type pattern whose binding is unnamed, so it is allowed anywhere a pattern is. case Point(_, _) first checks that the value is a Point, then ignores both components. A bare case _ would test nothing about the type.
Exercise
Rewrite case Square q, Triangle t -> "has corners"; so it compiles, and say when you would instead keep two separate cases.
Show answer
Write case Square _, Triangle _ -> "has corners";. Because the label declares no named bindings, the body does not need q or t. Keep two separate cases when the body needs a value from the matched object, such as side or base, because a shared label cannot bind names.