Sub topic 2
Case Ordering and Pattern Matching in Java
This chapter assumes Java classes, interfaces, inheritance, switch expressions, instanceof, casting, and basic generics. Examples use JDK 21 or newer.
Case ordering and dominance errors
A switch case is dominated when an earlier case already matches every value that the later case could match. Java rejects dominated cases because they can never run.
Put specific patterns before general patterns. Put guarded cases before their unguarded versions.
static String describe(Object value) {
return switch (value) {
case String s when s.isBlank() -> "blank string";
case String s -> "string";
case CharSequence cs -> "other character sequence";
default -> "other value";
};
}For example, placing CharSequence before String would make the String case dominated.
Sealed interfaces and exhaustive switches
A sealed interface restricts which classes can implement it. The compiler can therefore know the complete hierarchy.
sealed interface Shape permits Circle, Rectangle {}
record Circle(double radius) 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 Rectangle r -> r.width() * r.height();
};
}Exhaustive switches without `default`
This switch is exhaustive because it covers every permitted subtype. Omitting default lets the compiler detect a newly added subtype when the code is recompiled. A default case would hide that useful warning.
Records as data carriers
A record is a compact class for immutable data. Its components have generated accessors, such as radius() and width(). Records work well with pattern matching because their data shape is explicit.
Deconstructing records with record patterns
A record pattern checks a record and extracts its components in one operation.
record Point(int x, int y) {}
record Line(Point start, Point end) {}
static boolean isHorizontal(Object value) {
return switch (value) {
case Line(Point(var x1, var y1), Point(var x2, var y2)) ->
y1 == y2;
default -> false;
};
}The nested pattern deconstructs the Line, then both Point values. var asks the compiler to infer each component type.
Exercise
Why must case String s when s.isBlank() appear before case String s?
Show answer
The unguarded String case also matches blank strings, so placing it first would dominate the guarded case.