Sub topic 5
Case Ordering and Dominance Errors
Assume you know Java classes, inheritance, instanceof, casting, switch expressions, and basic generics. This chapter uses pattern matching finalized in Java 21. You will learn why the order of case labels matters and how the compiler detects unreachable cases.
What dominance means
A case is dominated when an earlier case already accepts every value that the later case could accept. The later case can never run, so Java rejects the switch at compile time.
For example, String implements CharSequence. Therefore, this order is invalid:
case CharSequence cs -> "characters";
case String s -> "a string";Every String is already a CharSequence. The first case catches every value that the second case could receive.
Put more specific patterns before more general patterns:
public class Main {
static String describe(Object value) {
return switch (value) {
case String s -> "string: " + s;
case CharSequence cs -> "other character sequence";
default -> "other value";
};
}
public static void main(String[] args) {
System.out.println(describe("hello"));
System.out.println(describe(new StringBuilder("hello")));
System.out.println(describe(42));
}
}The String case is more specific. The CharSequence case then handles other implementations, such as StringBuilder.
Order guarded cases from specific to general
A guarded pattern adds a condition with when. Place the guarded version before the unguarded version of the same pattern:
public class Main {
static String describe(Object value) {
return switch (value) {
case Integer i when i > 100 -> "large integer";
case Integer i -> "integer";
case String s when s.isBlank() -> "blank string";
case String s -> "non-blank string";
default -> "other value";
};
}
public static void main(String[] args) {
System.out.println(describe(150));
System.out.println(describe(12));
System.out.println(describe(" "));
System.out.println(describe("Java"));
}
}If case Integer i came first, it would accept every integer, including integers greater than 100. The guarded case would be dominated and rejected.
A non-constant guard usually does not dominate later cases because the compiler cannot prove that the guard always succeeds. Even so, placing the narrower condition first makes the intended behavior clear.
A practical ordering rule
Use this order:
- Exact or narrow types.
- Guarded cases.
- Broader related types.
- A final
defaultcase.
| Earlier case | Later case | Result |
|---|---|---|
| `CharSequence` | `String` | Later case is dominated |
| `String` | `CharSequence` | Valid |
| `Integer` with `when` | Un guarded `Integer` | Valid and useful |
| Un guarded `Integer` | Guarded `Integer` | Guarded case is dominated |
Visualizing dominance
Exercise
Exercise
Why does a String case need to appear before a CharSequence case?
Show answer
Because every String is a CharSequence. If CharSequence appears first, it accepts all Strings and dominates the later String case.