Sub topic 6
Exhaustive switch without a default branch
This chapter assumes you know Java switch expressions, records, and the basic sealed, permits, final and non-sealed rules from the earlier chapters. Pattern matching for switch requires Java 21 or later.
What exhaustive means
A switch is exhaustive when every possible value of the selector expression matches at least one case. A switch expression must be exhaustive, because it has to produce a value for every input. For ordinary types such as String or Object, the only way to get there is a default branch.
A sealed type changes this. The compiler knows the complete list of permitted subclasses, so a case for each one is enough. The default branch becomes unnecessary, and leaving it out is usually the better choice.
public class Main {
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
case Rectangle r -> r.width() * r.height();
};
}
public static void main(String[] args) {
System.out.println(area(new Square(3)));
System.out.println(area(new Rectangle(2, 5)));
}
}The program prints 9.0 and 10.0. The Shape declarations are nested here only so the file runs on its own. If you remove the Rectangle case, javac stops with this error:
the switch expression does not cover all possible input valuesWhy you should not add default
A default branch makes the switch exhaustive for any type, which also switches off the compiler's help. Suppose you later add Triangle to Shape:
- Without
default, every switch overShapefails to compile until you add aTrianglecase. The compiler lists each place you must update. - With
default, those switches keep compiling. Triangles silently fall into the fallback, which is often wrong, and the bug appears at run time.
A default that throws an exception only moves the failure from compile time to run time.
How the compiler checks coverage
The compiler works through the hierarchy from the selector type downward.
- A type pattern for a type
TcoversTand all of its subtypes. - A sealed type is covered when every one of its permitted direct subtypes is covered.
- This rule applies recursively, so intermediate sealed types can be covered either directly or through their own subtypes.
- An
enumis covered when all its constants are listed, or when a type pattern for the enum type is present. - A
non-sealedor non-final class is covered only by a pattern for that class (or a supertype). The compiler cannot know its subclasses.
Multi-level hierarchies
The recursion lets you match on leaf types, on an intermediate type, or on a mix of both.
public class Main {
sealed interface Vehicle permits Car, Truck {}
record Car(int seats) implements Vehicle {}
sealed interface Truck extends Vehicle permits Pickup, Lorry {}
record Pickup() implements Truck {}
record Lorry() implements Truck {}
static String leaves(Vehicle v) {
return switch (v) {
case Car c -> "car with " + c.seats() + " seats";
case Pickup p -> "pickup";
case Lorry l -> "lorry";
};
}
static String grouped(Vehicle v) {
return switch (v) {
case Car c -> "car";
case Truck t -> "some truck";
};
}
public static void main(String[] args) {
System.out.println(leaves(new Lorry()));
System.out.println(grouped(new Pickup()));
}
}Both methods are exhaustive. leaves names the leaf types. grouped uses Truck to cover Pickup and Lorry together. Pick the granularity you need at each call site.
Guards do not count toward coverage
A case with a when guard matches only some values, so the compiler never counts it as covering its type. You still need an unguarded case for the same type.
static String size(Shape shape) {
return switch (shape) {
case Circle c when c.radius() > 10 -> "big circle";
case Circle c -> "circle";
case Square s -> "square";
case Rectangle r -> "rectangle";
};
}If you delete the plain case Circle c, the switch no longer compiles, even though the guard looks like it handles the large circles. The compiler cannot prove anything about the guard expression.
Case order and dominance
Cases are tested from top to bottom. A case is dominated when an earlier case already matches everything it would match. That is a compile error:
this case label is dominated by a preceding case labelPut the more specific case first. In size above, the guarded Circle case must come before the plain one. Reversing them would make the guarded case unreachable, so javac rejects it. The same rule applies to type hierarchies: case Truck t followed by case Pickup p is an error, because every Pickup is already a Truck.
Records, nesting, and generics
Record patterns work with exhaustiveness. The compiler also checks that the patterns inside a record pattern cover each component's type.
public class Main {
sealed interface Expr {
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
}
static int eval(Expr e) {
return switch (e) {
case Expr.Num n -> n.value();
case Expr.Add(Expr l, Expr r) -> eval(l) + eval(r);
case Expr.Mul(Expr l, Expr r) -> eval(l) * eval(r);
};
}
public static void main(String[] args) {
Expr e = new Expr.Add(new Expr.Num(2), new Expr.Mul(new Expr.Num(3), new Expr.Num(4)));
System.out.println(eval(e));
}
}This prints 14. The patterns Expr l and Expr r match any Expr, so each record pattern covers its whole record type.
Generic sealed types also work. For Result<Integer>, the compiler considers only permitted subclasses that can actually be a Result<Integer>, so each case carries the type argument:
public class Main {
sealed interface Result<T> permits Ok, Err {}
record Ok<T>(T value) implements Result<T> {}
record Err<T>(String message) implements Result<T> {}
static String describe(Result<Integer> r) {
return switch (r) {
case Ok<Integer> ok -> "value " + ok.value();
case Err<Integer> err -> "error " + err.message();
};
}
public static void main(String[] args) {
System.out.println(describe(new Ok<>(7)));
System.out.println(describe(new Err<>("bad input")));
}
}Statements, null, and enums
Pattern switches used as statements must be exhaustive too. Only a legacy switch statement (old-style labels, no patterns, no null case) is allowed to leave values unhandled. As soon as you write case Circle c -> in a statement, javac requires full coverage.
Exhaustiveness does not cover null. A switch on a null selector throws NullPointerException unless you add case null. Do not add one by reflex. A NullPointerException is often the right response to a value that should never be null.
static String label(Shape shape) {
return switch (shape) {
case null -> "no shape";
case Circle c -> "circle";
case Square s -> "square";
case Rectangle r -> "rectangle";
};
}When an enum implements a sealed interface, you can list its constants as case labels. Java 21 allows qualified names such as case Level.HIGH, and listing every constant covers the enum.
What happens when the hierarchy changes later
Exhaustiveness is checked when you compile. The hierarchy can still change after a switch has been compiled, for example when a library adds a permitted subclass and your code is not recompiled. The compiler inserts a hidden failure path into every exhaustive switch that has no default.
| Situation | Result |
|---|---|
| You recompile after adding a permitted subclass | Compile error at each switch missing a case |
| You do not recompile, and a value of the new subclass arrives | `MatchException` at run time (Java 21) |
| The new subclass never arrives | Nothing happens, the old class files keep working |
The run-time failure is deliberate. It fails loudly instead of running a wrong branch. Java 21 throws MatchException here. Older versions threw IncompatibleClassChangeError for enum switches.
Common mistakes
- Adding
default -> throw new IllegalStateException()"to be safe". This disables the compile-time check, which is the safety you wanted. - Writing only guarded cases for a type and expecting coverage.
- Putting a supertype case above its subtypes and hitting a dominance error.
- Forgetting that a
non-sealedsubclass needs its own case, since the compiler cannot enumerate its descendants. - Assuming
case nullis implied. It is not.
Exercise
Given sealed interface Light permits Red, Green {} with record Red() implements Light {} and record Green() implements Light {}, does this switch compile? switch (light) { case Red r -> "stop"; case Green g when g.hashCode() > 0 -> "go"; }. If not, what is the smallest fix?
Show answer
It does not compile. The Green case has a when guard, so the compiler does not count it as covering Green, and the switch does not cover all possible input values. The fix is to add an unguarded case Green g after the guarded one, or to remove the guard.
Exercise
You maintain a sealed Shape hierarchy with 20 switches over it, none using default. You add a Triangle record to the permits list and recompile everything. What happens, and what happens if one of the 20 classes is not recompiled and later receives a Triangle?
Show answer
After recompiling, each of the 20 switches fails with "the switch expression does not cover all possible input values" (or the statement equivalent), so you must add a Triangle case to each. For the class that was not recompiled, a Triangle reaching its switch causes a MatchException at run time on Java 21.