Sub topic 5
Case ordering and dominance errors
This chapter assumes you can write a switch with type patterns and when guards, as covered in the earlier chapters on pattern labels and guards. It also assumes you know basic subtyping, such as String implementing CharSequence. You need JDK 21 or newer to compile the examples.
Why order matters now
In a classic switch over constants, case order rarely matters. Each constant matches exactly one value, so no two labels compete for the same input.
Pattern labels change this. case CharSequence cs and case String s both match the value "hi". The compiler has to say which one runs. The rule is simple: the switch tests labels from top to bottom, and the first label that matches wins.
If an earlier label can match every value that a later label could match, the later label can never run. Java treats that as an error instead of letting you ship dead code. This error is called a dominance error. The compiler reports it as "this case label is dominated by a preceding case label".
The basic dominance error
Here is the example from the plan. It does not compile.
public class DominanceBad {
static String bad(Object o) {
return switch (o) {
case CharSequence cs -> "chars";
case String s -> "string"; // error: dominated by CharSequence
default -> "other";
};
}
}String is a subtype of CharSequence. Every String is also a CharSequence, so the first case captures every string. The String case is unreachable.
The fix is to put the more specific type first.
public class DominanceFixed {
static String good(Object o) {
return switch (o) {
case String s -> "string";
case CharSequence cs -> "chars";
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(good("hi")); // string
System.out.println(good(new StringBuilder("hi"))); // chars
System.out.println(good(42)); // other
}
}The rule of thumb is to go from specific to general. Subtypes come before their supertypes, and the broadest label comes last.
Guards and dominance
A guard narrows what a label matches. The earlier label case Integer i when i > 100 matches only some integers, so it does not dominate a later case Integer i. Guarded labels followed by a broader unguarded label of the same type is the normal, correct shape.
public class Guards {
static String classify(Object o) {
return switch (o) {
case Integer i when i > 100 -> "large";
case Integer i when i < 0 -> "negative";
case Integer i -> "small non-negative";
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(classify(500)); // large
System.out.println(classify(-3)); // negative
System.out.println(classify(7)); // small non-negative
}
}Reverse the order and you get an error. An unguarded case Integer i matches every Integer, so any later Integer label, guarded or not, is dominated.
static String broken(Object o) {
return switch (o) {
case Integer i -> "int";
case Integer i when i > 100 -> "large"; // error: dominated
default -> "other";
};
}Two guarded labels of the same type never dominate each other. The compiler does not try to prove facts about your boolean expressions, so it cannot know whether i > 100 implies i > 50. It treats every guard as possibly false. The one exception is a guard that is the constant expression true. A label ending in when true is treated as unguarded, so it dominates like any unguarded label.
Because the compiler does not analyze guards, you are responsible for the logic among guarded labels. Consider this switch.
static String overlap(Object o) {
return switch (o) {
case Integer i when i > 50 -> "over 50";
case Integer i when i > 100 -> "over 100"; // compiles, but never selected
default -> "other";
};
}This compiles. The second label can never be reached for any input, because every value above 100 is also above 50. The compiler says nothing, and the output for 500 is over 50. Order guarded cases from the narrowest condition to the widest.
Dominance over constants
Constant labels, such as case 1 or enum names, can also be dominated. An unguarded pattern that covers the constant's type dominates it.
static String bad(Integer n) {
return switch (n) {
case Integer i -> "any";
case 1 -> "one"; // error: dominated by Integer i
};
}The fix is again to place the specific label first.
public class Constants {
static String good(Integer n) {
return switch (n) {
case 1 -> "one";
case Integer i -> "other: " + i;
};
}
public static void main(String[] args) {
System.out.println(good(1)); // one
System.out.println(good(9)); // other: 9
}
}The reverse is fine. A constant never dominates a pattern, because a constant matches only one value.
Default and null labels
The default label matches everything not matched earlier. For that reason it has an ordering rule of its own. A pattern label may not appear after default, because the pattern could never be reached.
static String bad(Object o) {
return switch (o) {
default -> "other";
case String s -> "string"; // error: dominated by default
};
}The usual advice is to put default last. The same applies to case null, default. A case null label that stands alone should come near the top, because null is not matched by type patterns anyway.
A related error appears when an unconditional pattern, which matches every value of the selector type, sits alongside default.
static String bad(Object o) {
return switch (o) {
case String s -> "string";
case Object x -> "object";
default -> "other"; // error: switch has both an unconditional pattern and a default
};
}You need only one catch-all. Pick case Object x if you want a name for the value, and default if you do not.
Order and sealed hierarchies
When the selector is a sealed type and the labels name unrelated permitted subtypes, order does not matter. Records Circle and Square do not overlap, so neither can dominate the other.
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 String name(Shape s) {
return switch (s) {
case Square q -> "square";
case Circle c -> "circle";
case Rectangle r -> "rectangle";
};
}Ordering matters only where one label's type contains another's. That happens with an interface and its implementors, a class and its subclasses, or a type and a guarded copy of the same type. It also matters when a sealed interface has a sub-interface that is itself sealed. Placing a label for the sub-interface before labels for its own permitted classes would dominate them.
Reading the compiler's complaint
Most dominance errors are fixed in one of three ways.
| Situation | Typical fix |
|---|---|
| Supertype label before a subtype label | Swap them so the subtype comes first |
| Unguarded label before a guarded label of the same type | Move the guarded label above the unguarded one |
| Pattern label after `default` | Move `default` to the end |
| Pattern label before a constant it covers | Move the constant above the pattern |
If the error points at a label you think is distinct, check what the earlier labels cover. A generic supertype like Number, Object, or CharSequence in an early position is the most common cause.
Order and evaluation
Because the switch tests labels in order, guards run in order too. A guard that has side effects, such as logging or reading a counter, runs only for the labels the switch actually reaches. Keep guards free of side effects, so that reordering cases does not change behavior beyond the choice of branch.
Reordering a switch with correct dominance is not always safe. Swapping two guarded labels of the same type is allowed by the compiler, but it can change which branch handles an input. Treat order as part of a guarded switch's meaning.
Exercise
The following switch does not compile. Which label is reported as dominated, why, and what is the smallest change that fixes it? switch (o) { case Number n -> "number"; case Integer i when i > 0 -> "positive int"; case Integer i -> "int"; default -> "other"; }
Show answer
Both Integer labels are dominated by the unguarded case Number n, because Integer is a subtype of Number and every Integer is already matched. The compiler reports the first one it reaches. The fix is to move case Number n below both Integer labels, keeping the guarded Integer label above the unguarded Integer label. The order is then Integer i when i > 0, Integer i, Number n, default.
Exercise
This switch compiles. For the input 500, which branch runs, and what should you change? switch (o) { case Integer i when i > 50 -> "over 50"; case Integer i when i > 100 -> "over 100"; default -> "other"; }
Show answer
It prints "over 50". The compiler does not analyze guards, so it accepts the second label even though it can never be selected. Put the narrower guard i > 100 first, then i > 50.