All topics
library
intermediate

Switch Expressions & Pattern Matching

Use modern switch as an expression with arrow syntax, pattern matching, and guarded patterns.

Java has evolved switch significantly:

Old switch = a vending machine with numbered buttons (limited to specific values). New switch = a smart assistant that can identify what you hand it (pattern matching) and always gives you something back (expression).

Key Concepts

1
Switch expressions (Java 14): switch returns a value, uses arrow syntax (->), and doesn't fall through. Pattern matching in switch (Java 21): switch cases can match on types, not just constants. Guarded patterns (Java 21): case Type t when condition -> ... adds conditions to type patterns.
2
Key features: - Arrow syntax: case "A" -> expr; (no fall-through, no break needed) - yield keyword: for multi-statement cases in expression form - Exhaustiveness: switch expressions must cover all possible values (or have default) - null handling: case null -> ... (Java 21+, previously switch threw NPE on null) - Multiple values per case: case 1, 2, 3 -> ...
3
Pattern matching switch replaces long if-else instanceof chains:
4
String describe(Object obj) { return switch (obj) { case Integer i -> "int: " + i; case String s -> "string: " + s; case null -> "null"; default -> "other"; }; }
5
With sealed types, the compiler enforces exhaustiveness without requiring default — it knows all subtypes.