Sub topic 2
Switching on types with pattern labels
This chapter assumes you know classic switch statements, switch expressions with arrows, instanceof with casts, and basic inheritance. It also assumes you have read the previous chapter on instanceof patterns. You need JDK 21 or newer.
What a pattern label is
A classic switch compares a value against constants. A pattern switch compares the value's runtime type against a type pattern. A type pattern is a type name followed by a binding variable, such as Integer i. When the value is an instance of that type, the case matches. The binding variable is then bound to the value already typed as Integer, so no cast is needed.
public class TypeSwitch {
static String format(Object o) {
return switch (o) {
case Integer i -> "int " + (i + 1);
case Long l -> "long " + l;
case String s -> "string of length " + s.length();
case int[] a -> "int array of length " + a.length;
default -> "other: " + o;
};
}
public static void main(String[] args) {
System.out.println(format(41));
System.out.println(format(7L));
System.out.println(format("hello"));
System.out.println(format(new int[] {1, 2, 3}));
System.out.println(format(3.5));
}
}This prints:
int 42
long 7
string of length 5
int array of length 3
other: 3.5The same logic written with instanceof needs a chain of if/else if tests and a cast in each branch. The switch states the intent directly: choose one branch based on the type of o. It is also a single expression that produces a value.
How the compiler and runtime treat it
The runtime tests the case labels from top to bottom. The first label whose type matches the value wins, and the rest are skipped. Several rules follow from this.
- Selector type. In Java 21 and 22, a switch that uses type patterns needs a reference-type selector.
Object, interfaces, classes, records, enums and arrays all work. A primitive selector such asintcannot use type patterns. - Binding scope. In an arrow case, the binding variable is in scope only in that case's right-hand side. You can reuse a name such as
sin different cases without a clash. - No fall-through into a binding. With old-style colon labels, a case that declares a binding cannot be reached by falling through from the case above. The compiler rejects this because the binding might be uninitialized.
- Exhaustiveness. A
switchexpression must cover every possible value. Aswitchstatement that uses patterns must do so as well. OverObjectyou almost always need adefaultor an unconditional pattern. The chapter on exhaustive switches covers the exception, which is sealed types.
Let me place the diagram in the proper construct below.
Switch expressions and switch statements
A switch expression yields a value. Each arrow right-hand side is an expression, a block that ends with yield, or a throw.
public class Lengths {
static int length(Object o) {
return switch (o) {
case String s -> {
String trimmed = s.trim();
yield trimmed.length();
}
case int[] a -> a.length;
case Object[] a -> a.length;
default -> throw new IllegalArgumentException("unsupported: " + o.getClass());
};
}
public static void main(String[] args) {
System.out.println(length(" hi "));
System.out.println(length(new int[] {4, 5, 6}));
System.out.println(length(new String[] {"a", "b"}));
}
}This prints 2, 3 and 2.
You can also use patterns in a switch statement, with arrows or colons. This is useful when each branch performs an action instead of producing a value.
public class Logger {
static void log(Object o) {
switch (o) {
case String s:
System.out.println("string " + s);
break;
case Integer i:
System.out.println("int " + i);
break;
default:
System.out.println("other");
}
}
public static void main(String[] args) {
log("x");
log(5);
log(2.0);
}
}Prefer arrows. They cannot fall through, so a forgotten break cannot silently run the next branch.
The default branch and unconditional patterns
A type pattern whose type is the selector's own type, or a supertype of it, matches every non-null value. This is called an unconditional pattern. It behaves like default, so a switch can have only one of the two.
static String label(CharSequence cs) {
return switch (cs) {
case String s -> "String";
case StringBuilder sb -> "StringBuilder";
case CharSequence other -> "some other CharSequence";
};
}Here case CharSequence other is unconditional, so no default is needed and adding one is a compile error. The unconditional case must come last, because it would otherwise make the later cases unreachable. The chapter on dominance explains that rule.
Null and generics
If the selector is null and no case null exists, the switch throws NullPointerException. This matches the behavior of classic switches. A later chapter shows how case null changes it.
Generic type patterns have one restriction. The type in the pattern must not require an unchecked cast from the selector type.
static String kind(Object o) {
return switch (o) {
// case List<String> l -> "strings"; // compile error: unchecked cast from Object
case java.util.List<?> l -> "list of size " + l.size();
default -> "not a list";
};
}
static int count(java.util.Collection<String> c) {
return switch (c) {
case java.util.List<String> l -> l.size(); // allowed: checked by the selector type
default -> c.size();
};
}The first is rejected because the runtime cannot verify the element type after erasure. The second is allowed because the selector's Collection<String> already fixes the element type.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "the switch expression does not cover all possible input values" | An `Object` selector with no `default` | Add `default`, or an unconditional pattern |
| "duplicate default label" or "switch has both an unconditional pattern and a default label" | An unconditional pattern together with `default` | Keep only one |
| `NullPointerException` at the switch line | The selector was `null` and there was no `case null` | Check for null first, or add `case null` |
| "this case label is dominated by a preceding case label" | A supertype case appears before a subtype case | Put the more specific type first |
| "illegal fall-through to a pattern" | A colon-form case with a binding is reached from the case above | End the previous case with `break`, or use arrows |
| "Object cannot be safely cast to List<String>" | A generic pattern that needs an unchecked cast | Use `List<?>` or give the selector a more specific type |
Behavior to remember
- Cases are tested in source order, so ordering matters as soon as types are related by inheritance.
- A binding variable is a fresh local variable. Assigning to it does not change the selector.
- The type of the binding is the pattern type, so you can call its methods directly.
- A pattern switch is not a replacement for polymorphism. Use it when the types are data that you do not control, or when the operation does not belong on the types themselves.
Exercise
What does this code print, and why? Object o = 3; String r = switch (o) { case Number n -> "number"; case Integer i -> "integer"; default -> "other"; }; Fix it if it does not compile.
Show answer
It does not compile. Integer is a subtype of Number, so the case Integer i label is dominated by the earlier case Number n: no value could reach it. Swap the two cases so Integer i comes first. Then the code prints nothing by itself, but r is "integer" for the value 3.
Exercise
A method has the signature static String name(Object o) and uses switch (o) with only case String s and case Integer i, both returning a string. Why does it fail to compile, and what are two ways to fix it?
Show answer
The switch expression is not exhaustive, because Object has many more subtypes than String and Integer. Fix it by adding a default branch, or by adding an unconditional pattern such as case Object other. You cannot use both together.