Sub topic 14
Where This Leads: Patterns in `switch`
Assume you know Java classes, inheritance, casts, instanceof, Boolean operators, and equals. This chapter uses Java 21 or later. Pattern matching in switch applies the same idea as a type pattern in instanceof, but it can choose among several type cases.
From an `if` chain to a `switch`
Suppose one value can have several runtime types. With instanceof, you might write:
static String describe(Object value) {
if (value instanceof String s) {
return "text: " + s;
} else if (value instanceof Integer i) {
return "integer: " + i;
} else {
return "other";
}
}A pattern switch expresses the alternatives directly:
public class SwitchPatterns {
static String describe(Object value) {
return switch (value) {
case String s -> "text: " + s;
case Integer i -> "integer: " + i;
case null -> "missing";
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(describe("hello"));
System.out.println(describe(42));
System.out.println(describe(null));
System.out.println(describe(3.14));
}
}Each type pattern tests the selector and creates a binding variable for its case. The variable s exists only in the String arm. The variable i exists only in the Integer arm.
A switch expression produces a value. Arrow cases make each result clear, so this example does not need break or yield.
Exhaustiveness and case order
A switch expression must be exhaustive. It must handle every possible input. The default case handles types not listed explicitly. For a switch statement, Java does not always require default, but adding one can still make the behavior clear.
Cases are tested in order, and a broad pattern can hide a later narrow pattern:
static String classify(Object value) {
return switch (value) {
case String s when s.isBlank() -> "blank text";
case String s -> "non-blank text";
default -> "not text";
};
}The guarded case uses when to add a condition. The first case matches a String and then checks isBlank(). If the guard is false, Java tries the next compatible case.
A broad case must come after a narrow case:
static String badOrder(Object value) {
return switch (value) {
// Does not compile: this case dominates the String case.
// case Object o -> "object";
// case String s -> "text";
default -> "other";
};
}A case that matches every object would make the later String case unreachable. This rule prevents confusing code.
Null in a pattern switch
A traditional switch usually throws NullPointerException when its selector is null. A pattern switch can handle null explicitly:
static String describeNull(Object value) {
return switch (value) {
case null -> "no value";
case String s -> "text";
default -> "other";
};
}The String pattern does not match null. The explicit case null documents and controls that behavior.
The connection to record patterns
Pattern switches combine naturally with record patterns. A record pattern checks the record type and extracts its components:
record Point(int x, int y) {}
static String describePoint(Object value) {
return switch (value) {
case Point(int x, int y) -> "x=" + x + ", y=" + y;
default -> "not a point";
};
}This extends the same progression: instanceof first tests a type, a type pattern also binds the value, and a record pattern binds values inside the object. Switch patterns are useful when several shapes need different behavior.
Exercise
Write a Java 21 switch expression that returns "long" for a String longer than five characters, "short" for another String, and "other" for every different value.
Show answer
return switch (value) { case String s when s.length() > 5 -> "long"; case String s -> "short"; default -> "other"; };