Sub topic 3
Sharing One Switch Case Across Several Patterns
This chapter assumes you know Java records, sealed types, and pattern matching in switch. Java 22 finalized unnamed variables and patterns through JEP 456.
One result for several patterns
A pattern such as Circle _ matches a Circle without creating a name for the matched object. Because it declares no named binding, several patterns can share one case label:
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 shape) {
return switch (shape) {
case Circle _, Square _ -> "has a simple outline";
case Triangle _ -> "has three sides";
};
}
}The underscore says that the value is needed for matching, but its contents are not needed in the case body. A named pattern variable would prevent this grouping if the names were unused.
Where `_` is not allowed
An underscore is not a universal replacement for every Java identifier.
- It cannot name a field.
- It cannot name a method or constructor parameter.
- It cannot be used as a standalone top-level pattern such as
case _. - An unnamed pattern
_is used inside record patterns to ignore a component. It is different from an unnamed pattern variable such asCircle _.
For example, this record pattern keeps the first coordinate and ignores the second:
record Point(int x, int y) {}
static int xCoordinate(Object value) {
if (value instanceof Point(int x, _)) {
return x;
}
return -1;
}Versions and migration
The feature was previewed in Java 21 and became permanent in Java 22. Code using the preview version may require preview compiler and runtime flags. When migrating older code, replace unused names gradually and compile with the target Java release. Do not replace a name if documentation, debugging, or future changes benefit from it.
Choosing a clear form
Use _ when a value has no meaningful role beyond satisfying a declaration or pattern. Keep a descriptive name when the value explains the algorithm, may be logged, or is likely to be used soon.
Exercise
Why can case Circle _, Square _ -> share one switch result?
Show answer
Neither pattern declares a named binding, so the case body has no conflicting or unused variable names.