Sub topic 12
Ignoring components with unnamed patterns (Java 22)
This chapter assumes you can write record patterns, including nested ones, and that you know sealed interfaces and exhaustive switches from earlier chapters. You need JDK 22 or newer. In JDK 21, unnamed patterns and variables are only a preview feature.
The problem: names you never use
Record patterns bind a variable for every component you list. Here is a horizontal-line check from the previous chapter:
case Line(Point(var x1, var y1), Point(var x2, var y2)) -> y1 == y2;The variables x1 and x2 are declared and never read. A reader has to check that they really are unused. Some linters and IDEs flag them as warnings. Before Java 22 you could not drop a component. You had to invent a throwaway name for it.
Java 22 (JEP 456) fixes this with the unnamed pattern _ and unnamed variables. The underscore says "there is a value here and I don't care about it."
The unnamed pattern `_`
An unnamed pattern matches any value and binds nothing. You can write it only as a component inside a record pattern:
record Point(int x, int y) {}
record Line(Point start, Point end) {}
static boolean isHorizontal(Object o) {
return o instanceof Line(Point(_, var y1), Point(_, var y2)) && y1 == y2;
}The check now names only the values it uses, the two y coordinates. The two _ components still have to exist, so a Point must have exactly two components. Only their values are ignored.
An unnamed pattern is also unconditional. It matches whatever the component holds, including null. This is the same rule as for var x, which also accepts null. The compiler can therefore treat a pattern made of _ and var components as covering every value of that component type.
Unnamed variables: type patterns with `_`
Sometimes you do want the type test but not the variable. Write the type and replace the name with _:
case Circle _ -> "round";This is still a type pattern. It checks that the value is a Circle. It just declares no binding variable. Compare the forms:
| Form | Tests the type? | Binds a variable? | Matches `null`? | Where it can appear |
|---|---|---|---|---|
| `Circle c` | Yes | `c` | No | Anywhere a pattern is allowed |
| `Circle _` | Yes | None | No | Anywhere a pattern is allowed |
| `var c` | No | `c` | Yes | Inside a record pattern only |
| `var _` | No | None | Yes | Inside a record pattern only |
| `_` | No | None | Yes | Inside a record pattern only |
var _ and _ mean the same thing in a record component. Use whichever your team finds clearer. var _ is closer to the pre-Java 22 style, and _ is shorter.
A complete example
This program is complete. Save it as UnnamedDemo.java and run it with java UnnamedDemo.java on JDK 22 or newer.
sealed interface Shape permits Circle, Rectangle, Square {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
record Square(double side) implements Shape {}
record Box<T>(T content) {}
public class UnnamedDemo {
static String name(Box<Shape> box) {
return switch (box) {
case Box<Shape>(Circle _) -> "box holding a circle";
case Box<Shape>(var _) -> "box holding another shape";
};
}
static String family(Shape s) {
return switch (s) {
case Circle _ -> "round";
case Rectangle _, Square _ -> "angular";
};
}
public static void main(String[] args) {
System.out.println(name(new Box<>(new Circle(1))));
System.out.println(name(new Box<>(new Square(2))));
System.out.println(name(new Box<>(null)));
System.out.println(family(new Rectangle(1, 2)));
}
}The output is:
box holding a circle
box holding another shape
box holding another shape
angularThree details are worth noting:
- The second case in
nameusesvar _, which matches every possible content value. The switch is exhaustive without adefault. - The third call passes a box whose content is
null.Circle _does not matchnull, butvar _does. That is why the box counts as "holding another shape". If you wanted to treat an empty box separately, you would put aBox<Shape>(null)case before thevar _case. case Rectangle _, Square _lists two patterns in one label. This is allowed only because neither pattern declares a named variable. Both branches share one body, and the body has no variable to read. Writingcase Rectangle r, Square sis a compile error, because the body could not know which variable is set.
Unnamed patterns in a larger program
Unnamed patterns help most when a pattern is a structural test and you want to say which parts matter. Here is a function over the expression tree from the earlier evaluator chapter:
sealed interface Expr permits Const, Add, Mul, Neg {}
record Const(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
record Neg(Expr operand) implements Expr {}
public class ExprDemo {
static boolean isZeroProduct(Expr e) {
return switch (e) {
case Mul(Const(var a), _) when a == 0 -> true;
case Mul(_, Const(var b)) when b == 0 -> true;
default -> false;
};
}
static boolean isLeaf(Expr e) {
return switch (e) {
case Const _ -> true;
case Add _, Mul _, Neg _ -> false;
};
}
public static void main(String[] args) {
Expr zero = new Mul(new Const(0), new Neg(new Const(7)));
System.out.println(isZeroProduct(zero));
System.out.println(isLeaf(zero));
}
}This prints true and then false. The first case reads as "a Mul whose left side is a constant a, and whose right side I ignore." The _ makes it clear that the right side never matters, even if it is a huge subtree.
isLeaf has no default. Because Expr is sealed, listing all three non-leaf types in one label is exhaustive. If someone later adds a fifth permitted subtype, this switch stops compiling. That is the safety benefit of sealed types, and _ does not weaken it.
Unnamed variables outside patterns
JEP 456 also lets you use _ as the name of a variable whose value is never read. This applies to any declaration where the name is required by syntax but irrelevant:
import java.util.List;
import java.util.Map;
public class UnnamedVariables {
static int parseOrDefault(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException _) {
return -1;
}
}
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Linus");
int count = 0;
for (String _ : names) {
count++;
}
System.out.println(count);
Map<String, Integer> ages = Map.of("Ada", 36);
ages.forEach((_, age) -> System.out.println(age));
System.out.println(parseOrDefault("x42"));
}
}This prints 3, 36 and -1. The same notation works for local variables (var _ = queue.poll();) and for resources in try-with-resources. It also works in lambda parameters, as shown above. The meaning is the same everywhere: the declaration exists, but nothing can refer to it.
Rules and common errors
_is not a readable name. You cannot write_ + 1or pass_to a method. Each_is independent, so you can use it several times in the same scope.case Add(_, _)is legal._cannot be a whole top-level pattern.case _ ->ando instanceof _are errors. Usedefaultfor a catch-all, or write a type pattern such asObject _. The unnamed pattern exists only for record components.- A multi-pattern label cannot bind names.
case A _, B _is fine.case A a, B bis an error. - Guards cannot see unnamed variables. A
whenclause can use only named bindings. If the guard needs a value, name it. - Older release targets reject
_. Compiling with--release 21gives an error, because the underscore is reserved. Since Java 9,_has not been legal as an ordinary identifier. On JDK 21 you can try the feature only with--enable-preview --release 21. Circle _is not the same as_. The first rejectsnulland non-circles. The second accepts anything. When you replace a named variable, keep the type if the type was doing real work.
Exercises
Exercise
In the following switch, which case matches new Box<Shape>(null), and why? Is the switch exhaustive?
switch (box) {
case Box<Shape>(Circle ) -> "circle";
case Box<Shape>(var ) -> "other";
}
Show answer
The second case matches. Circle _ is a type pattern, and a type pattern never matches null, so the first case fails. var _ is unconditional and matches any value, including null. The switch is exhaustive because var _ covers every possible content value. No default is needed.
Exercise
Rewrite this case so it declares no unused variables, and explain why the version with two named bindings would not compile if you merged the two cases into one label: case Rectangle r -> "angular"; case Square s -> "angular";
Show answer
Write case Rectangle _, Square _ -> "angular";. A single case label with several patterns is allowed only when none of the patterns declares a named binding, because the body could not know which of r or s is set. So case Rectangle r, Square s -> ... is a compile error. The unnamed form has no binding and is accepted.
Exercise
Why is case _ -> "anything"; rejected in a switch over Object, and what do you write instead?
Show answer
The unnamed pattern _ is allowed only as a component inside a record pattern. It cannot be a top-level pattern. Use default -> "anything"; as the catch-all. Alternatively, use a type pattern with an unnamed variable, case Object _ -> "anything";, which is also legal.