Sub topic 10
Where _ is not allowed
This chapter assumes you know the forms of _ from earlier chapters: unnamed locals, catch and lambda parameters, unnamed pattern variables (Type _), and the unnamed pattern (_). Here you learn where the compiler rejects _. These are Java 22 rules (JEP 456).
The rule behind the restrictions
_ means "declare this, but never refer to it." It only makes sense where a declaration could go unread without hurting anything. Two kinds of places break that idea:
- Places where other code can see or call the name, such as fields and method parameters.
- Places where there is nothing to match, such as a bare
_that is not inside a record pattern.
You also can never read _. It is not a variable you can use later, so int _ = 5; System.out.println(_); does not compile.
Declarations that do not accept _
| Location | Allowed? | Why |
|---|---|---|
| Local variable in a block | Yes, with an initializer | Nothing can read it later |
| Enhanced `for` variable | Yes | The element is ignored |
| Resource in try-with-resources | Yes | The resource is only closed |
| Catch parameter | Yes | The handler ignores the exception |
| Lambda parameter | Yes | The caller supplies a value you ignore |
| Field | No | Other code could refer to it |
| Method or constructor parameter | No | It is part of the method's signature and documentation |
| Record component in the header | No | It defines an accessor and a field |
| Top-level `_` in a pattern | No | `_` is not a pattern by itself |
A local variable needs an initializer. This is legal:
int _ = compute();This is not, because the variable could never be assigned later:
int _;Patterns: nested only
The unnamed pattern _ matches anything, but only as a component inside a record pattern. At the top level you must name a type. Use Type _ (an unnamed pattern variable) instead.
record Point(int x, int y) {}
record Line(Point start, Point end) {}
class Checks {
// Legal: _ is nested inside a record pattern.
static boolean isLine(Object o) {
return o instanceof Line(_, _);
}
// Legal: a type pattern with an unnamed variable.
static boolean isPoint(Object o) {
return o instanceof Point _;
}
// Illegal, so it is left as comments:
// static boolean any(Object o) { return o instanceof _; }
// static int size(int _) { return 1; }
// private final int _ = 0;
// record Pair(int _, int _) {}
public static void main(String[] args) {
System.out.println(isLine(new Line(new Point(0, 0), new Point(1, 1))));
System.out.println(isPoint("text"));
}
}The same reasoning applies in switch. case _ -> is not allowed. To catch everything else, use default, or a named type pattern such as case Object _ ->. If the selector is a sealed type that your cases already cover, no extra case is needed.
Multiple patterns in one case
Several patterns can share a case label only if none of them declares a named binding.
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 Describe {
static String describe(Shape s) {
return switch (s) {
case Circle _ -> "round";
case Square _, Triangle _ -> "has corners";
};
}
}If you wrote case Square sq, Triangle t ->, the compiler would reject it. The body would not know which variable was bound, so the labels cannot be combined.
Checking a declaration
Common errors
- Using
_as a parameter name in a method. Choose a real name, or restructure so the method does not take that value. - Declaring
int _;with no initializer. Assign a value, or drop the declaration. - Reading
_after declaring it. Give the variable a name if you need it. - Writing
case Square sq, Triangle t. UseSquare _, Triangle _, or write separate cases.
Exercise
Which of these lines does not compile in Java 22? (a) for (var _ : list) { n++; } (b) if (o instanceof Line(_, Point(int y, _))) { ... } (c) static void log(String _) { ... } (d) catch (IOException _) { ... }
Show answer
(c). Method parameters cannot be unnamed, because they are part of the method's signature. The other lines are valid: (a) an unnamed loop variable, (b) nested unnamed patterns inside record patterns, (d) an unnamed catch parameter.
Exercise
Why is o instanceof _ illegal, and what is the legal way to write a type test that ignores the value?
Show answer
The unnamed pattern _ is only allowed nested inside a record pattern, so it cannot stand alone. Write a type pattern with an unnamed variable instead, for example o instanceof Point _.