Sub topic 7
Exhaustive switches without default
This chapter covers how the compiler decides that a switch handles every possible input, and why leaving out default is often the safer choice. It assumes you know sealed interfaces, records, type patterns in switch and when guards from the earlier chapters, and that you have JDK 21 or newer.
What exhaustive means
A switch is exhaustive when every possible value of the selector expression matches at least one case label. Java enforces this in these situations:
| Construct | Must be exhaustive? |
|---|---|
| Switch expression (any selector) | Always |
| Switch statement using pattern labels or `case null` | Yes (since Java 21) |
| Old-style switch statement over an enum, string or int with constant labels only | No |
If the compiler cannot prove coverage, it rejects the code with the message "the switch expression does not cover all possible input values" (or "the switch statement ..." for a statement).
A selector type can be covered in three ways:
- A
defaultlabel. - An unguarded pattern that matches the whole selector type, such as
case Object ofor anObjectselector. This is called a total pattern. - Labels that cover every permitted subtype of a sealed type, every constant of an enum, or every combination of a record's component patterns.
This chapter concentrates on the third way, because it is the only one where the compiler checks your work against the type hierarchy.
Sealed hierarchies
A sealed interface lists all its direct subtypes in permits. The compiler knows this list is final, so it can check that a switch mentions each one.
public class ShapeDemo {
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 {}
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
case Square s -> s.side() * s.side();
};
}
public static void main(String[] args) {
System.out.println(area(new Square(3)));
System.out.println(area(new Rectangle(2, 4)));
}
}This prints 9.0 and then 8.0. There is no default, and none is needed.
Why leaving out default helps
Suppose you add record Triangle(double base, double height) implements Shape {} and list it in permits. The area method above stops compiling. The compiler points at the switch, and you add the missing case.
If area had a default -> 0.0, the code would still compile. Triangles would silently get an area of zero. A default on a sealed type turns a compile-time check into a runtime bug waiting to happen.
Hierarchies with more than one level
The compiler follows sealed types down through the hierarchy. If Shape permits a sealed interface Polygon, you can cover Polygon with one label, or cover each of its permitted subtypes separately. Both are exhaustive. An abstract sealed class works the same way, but a non-abstract sealed class also needs its own label, because instances of the class itself can exist.
Enums work like a sealed type whose subtypes are constants. A switch expression that names every constant needs no default. An enum can also implement a sealed interface. Since Java 21 you can mix a type pattern for one record and qualified enum constants for another in the same switch.
Guards do not count
The compiler cannot evaluate a when condition at compile time, so it assumes a guarded case might not match. Guarded cases never contribute to exhaustiveness, with one exception: a guard that is the constant true.
// Does not compile: the switch expression does not cover all possible input values
static String sign(Integer n) {
return switch (n) {
case Integer i when i > 0 -> "positive";
case Integer i when i <= 0 -> "non-positive";
};
}You can see that the two guards cover every integer, but the compiler cannot. Remove the second guard to make the case unguarded:
static String sign(Integer n) {
return switch (n) {
case Integer i when i > 0 -> "positive";
case Integer i -> "non-positive";
};
}The same rule applies to sealed types. If you write case Circle c when c.radius() > 0, you still need an unguarded case Circle later, or a default, to cover circles.
Exhaustiveness with record patterns
Record patterns take part in the same analysis. For a record with sealed component types, the compiler checks that your patterns cover every combination of component subtypes.
public class PairDemo {
sealed interface Answer permits Yes, No {}
record Yes() implements Answer {}
record No() implements Answer {}
record Pair(Answer first, Answer second) {}
static String combine(Pair p) {
return switch (p) {
case Pair(Yes a, Yes b) -> "both yes";
case Pair(Yes a, No b) -> "first yes";
case Pair(No a, Yes b) -> "second yes";
case Pair(No a, No b) -> "both no";
};
}
public static void main(String[] args) {
System.out.println(combine(new Pair(new Yes(), new No())));
System.out.println(combine(new Pair(new No(), new No())));
}
}The output is first yes and then both no. There are two permitted types in each of two positions, so four cases are needed. Delete any one of them and the code stops compiling. You can also use var or a type pattern for the whole component to cover several combinations at once. For example, case Pair(No a, var b) covers both cases where the first answer is No.
Generic sealed types
For a generic sealed type, the compiler only requires the subtypes that can exist for the type arguments in the selector. If a subtype implements Expr<Integer> only, a switch over Expr<String> does not need a case for it. This keeps typed expression trees from requiring impossible branches.
null and exhaustiveness
Exhaustiveness covers the values of the type, not null. A pattern switch without case null throws NullPointerException when the selector is null, even if the switch covers every subtype. A total pattern also does not match null unless you write case null or case null, default. If null is a legal input, add case null explicitly. If it is not, leave the switch as is and let the exception report the bug.
Failure at run time
The compiler checks exhaustiveness against the classes it sees at compile time. If you add a new permitted subtype to a library and do not recompile the code that switches over it, that code still runs. When an instance of the new subtype arrives, the switch throws MatchException because no label matches. Java 21 also throws MatchException in this situation for enum switch expressions without default. Earlier versions threw IncompatibleClassChangeError. The next chapters in this series return to this exception.
Common mistakes
- Adding
defaultto a sealed switch "just in case". This hides new subtypes from the compiler. Usedefaultonly when you intentionally want one fallback behaviour for all remaining types. - Expecting guarded cases to count. Always keep an unguarded case for each type that has guards.
- Forgetting a permitted subtype that lives in a nested hierarchy. Read the compiler message, which names a missing type.
- Assuming a pattern switch statement over an enum with constant labels is checked. A classic switch statement without patterns is not required to be exhaustive, so a missing constant is silent.
Exercise
Exercise
Given sealed interface Vehicle permits Car, Truck, Bike {} where all three are records, does the following compile? If not, how do you fix it with the smallest change and no default?
static String label(Vehicle v) {
return switch (v) {
case Car c -> "car";
case Truck t -> "truck";
case Bike b when b.gears() > 1 -> "geared bike";
};
}
Show answer
It does not compile. The Bike case is guarded, so the compiler does not count it as covering Bike, and the switch expression does not cover all possible input values. Add an unguarded case Bike b -> "bike"; after the guarded case. The guarded case must come first, or the unguarded one would dominate it.
Exercise
A switch over Pair(Answer first, Answer second) has the cases Pair(Yes a, var b) and Pair(No a, Yes b). Which single case must you add to make it exhaustive?
Show answer
case Pair(No a, No b). The first case covers every pair that starts with Yes. The second covers No followed by Yes. The only remaining combination is No followed by No.