Pattern Matching in Java
Simplify type checks with pattern matching for instanceof (Java 16+), and write exhaustive, readable switch expressions with pattern matching (Java 21).
Pattern Matching for instanceof (Java 16+)
1. Old Way — instanceof + Manual Cast
Before Java 16, you had to check the type and then manually cast — two separate steps, verbose and error-prone.
2. Pattern Matching instanceof (Java 16+)
With pattern matching, the cast is done automatically and the variable is bound in one step: `obj instanceof String s`.
3. Pattern Matching with Guard Condition
Add a `&&` guard condition directly in the `instanceof` expression to combine type check and value check.
Pattern Matching in switch (Java 21+)
1. Type Patterns in switch
Java 21 allows `case Type varName ->` in switch expressions. Each arm automatically casts the value.
2. Guarded Patterns in switch
Add a `when` condition to a switch case to further refine the match (Java 21+).