Sub topic 1
From `instanceof` and Casts to Type Patterns
Prerequisites
You should know Java classes, interfaces, inheritance, instanceof, casts, and switch expressions. Examples use JDK 21 or newer.
From `instanceof` and Casts to Type Patterns
Before pattern matching, checking a value's type required two steps:
if (value instanceof String) {
String text = (String) value;
return text.length();
}A type pattern combines the test and cast. The variable text is available only where Java knows that the value is a String.
if (value instanceof String text && !text.isEmpty()) {
return text.length();
}The && condition is safe because the second condition runs only after the type test succeeds.
Switching on Types with Pattern Labels
A switch expression can select a branch using the runtime type of its selector. A runtime type is the class an object actually has while the program runs.
public class PatternDemo {
static String describe(Object value) {
return switch (value) {
case String text -> "string of length " + text.length();
case Integer number -> "integer " + number;
default -> "other value";
};
}
public static void main(String[] args) {
System.out.println(describe("Java"));
System.out.println(describe(42));
}
}Each pattern both checks the type and binds a variable. The default label handles values that match neither pattern.
Handling `null` with `case null`
A type pattern does not match null. Without an explicit case null, a switch over a null selector throws NullPointerException.
Use case null when null is a valid input:
static String describe(Object value) {
return switch (value) {
case null -> "missing";
case String text -> "string";
default -> "other";
};
}Refining a Case with `when` Guards
A when guard adds a condition to a pattern. Put the more specific guarded case before the general case.
static String size(Object value) {
return switch (value) {
case Integer n when n > 100 -> "large";
case Integer n -> "普通";
default -> "not an integer";
};
}Exercise
What does a switch need to return "blank" for an empty String and "text" for every other String?
Show answer
Put case String s when s.isEmpty() -> "blank"; before case String s -> "text";.