Java 38: Pattern Matching for instanceof & switch
easy⏱ 5 mincoursejava
instanceof pattern (Java 16)
if (obj instanceof String s) { /* s is a String here */ } — the binding variable (s) is in scope only inside the true branch. Also scopes to the && chain and the following if-else. Replaces the old instanceof-then-cast idiom.
// Old
if (o instanceof String) {
String s = (String) o;
return s.length();
}
// Modern
if (o instanceof String s) return s.length();
switch patterns (Java 21)
switch (shape) { case Circle c -> Math.PI * c.r() * c.r(); case Square s -> s.side() * s.side(); }. Deconstructs records in-place. On sealed hierarchies, the compiler enforces exhaustiveness — missing a permitted type is a compile error.
double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Rectangle(var w, var h) -> w * h; // record deconstruction
case Triangle t -> 0.5 * t.base() * t.height();
};
}
Guarded patterns
case Point p when p.x() > 0 && p.y() > 0 -> "Q1" — a when clause refines a pattern with an extra predicate. Evaluated after the type match. Useful for state-machine decisions without nested ifs.
Build a tax calculator
Use a tagged-union Income = Salary | Freelance | Dividend | Capital (TS equivalent of a sealed hierarchy). Write tax(income) using a switch (income.kind) with exhaustive checks and when-style guards ('high earner bracket'). Run for 4 income samples.
Prefer switch expressions over if-chains
An if (x instanceof A a) return ...; else if (x instanceof B b) return ...; chain is mechanical. switch (x) { case A a -> ...; case B b -> ...; } is shorter, harder to accidentally fall through, and exhaustive-checked on sealed types. Modernize your code — it pays off.
Quiz: Null in a sealed switch
switch (sealedRef) when the reference could be null — does it throw NPE? Only if there's no case null branch. Java 21 switches can include case null -> ... or case null, default -> ... — if you omit both, null triggers an NPE, matching classic switch behavior.