Sub topic 2
Switching on Types with Pattern Labels
This chapter assumes you know Java classes, inheritance, instanceof, casting, classic switch statements, switch expressions, and basic generics. The examples use Java 21 or newer.
A type pattern combines a type test with a variable binding. In case String s, Java checks whether the value is a String and, if it is, binds that value to s. You can use s directly without writing a cast.
Replacing `instanceof` and casts
Before pattern matching, code often repeated the type information:
static String describe(Object value) {
if (value instanceof String) {
String text = (String) value;
return "string of length " + text.length();
}
if (value instanceof Integer) {
Integer number = (Integer) value;
return "integer " + number;
}
return "other value";
}A type pattern makes each test and cast one operation:
static String describe(Object value) {
if (value instanceof String text) {
return "string of length " + text.length();
}
if (value instanceof Integer number) {
return "integer " + number;
}
return "other value";
}The pattern variable is available only where Java knows that the pattern matched. This rule is called flow scoping. For example, text is available on the right side of && because the first condition must succeed before the second condition runs.
Type patterns in switch
A switch expression can select a branch according to the runtime type of its selector. The runtime type is the actual class of an object, rather than the type of the variable that refers to it.
public class TypeSwitchDemo {
static String describe(Object value) {
return switch (value) {
case String text -> "string of length " + text.length();
case Integer number -> "integer " + number;
case Double number -> "decimal " + number;
default -> "other value: " + value;
};
}
public static void main(String[] args) {
System.out.println(describe("Java"));
System.out.println(describe(42));
System.out.println(describe(3.14));
System.out.println(describe(true));
}
}The selector has type Object, so it can refer to values of many unrelated types. Each pattern label tests one possible type. The arrow (->) produces the result for that case, so the switch expression has a value that the method returns.
A default label handles values that do not match any listed type. It is needed here because Object is an open type: other classes can exist now or be created later.
Ordering and compatible types
Pattern labels must be reachable. A broad pattern can make a later, narrower pattern impossible to match:
static String bad(Object value) {
return switch (value) {
case CharSequence sequence -> "characters";
case String text -> "string";
default -> "other";
};
}This does not compile. Every String is a CharSequence, so the first case already accepts every value that the String case could accept. Put the more specific pattern first:
static String good(Object value) {
return switch (value) {
case String text -> "string";
case CharSequence sequence -> "characters";
default -> "other";
};
}The compiler reports this situation as a dominance error. Order cases from most specific to most general when their types are related.
Exercise
Why must case String text appear before case CharSequence sequence?
Show answer
String implements CharSequence, so the broader CharSequence pattern would match every String first and dominate the String case.