Working with Pattern Matching

1. Using Pattern Matching for instanceof (Java 16+)

FormExample
Type patternif (o instanceof String s) { ... use s ... }
Negatedif (!(o instanceof String s)) return; // s in scope after
Combinedif (o instanceof Integer i && i > 0)

2. Using Switch Expressions (Java 14+)

FeatureDetail
Arrow formcase A -> expr;
No fall-throughEach arrow is independent
Multi-labelcase A, B -> ...
yieldBlock-form return value

Example: Switch expression

int days = switch (month) {
    case JAN, MAR, MAY, JUL, AUG, OCT, DEC -> 31;
    case APR, JUN, SEP, NOV -> 30;
    case FEB -> { yield isLeap ? 29 : 28; }
};

3. Using Pattern Matching in Switch (Java 21+)

PatternForm
Typecase Integer i ->
Recordcase Point(int x, int y) ->
Guardedcase Integer i when i > 0 ->
nullcase null -> ...
Defaultdefault ->

4. Understanding Type Patterns

AspectDetail
BindingPattern variable typed
Total patternType pattern matches non-null
GenericsErasure rules apply

5. Using Guarded Patterns (when clause)

FormBehavior
case T t when expr ->Match only if expr true
OrderEarlier guards take precedence
Binding scopePattern var visible in guard

Example: Guarded

String describe(Object o) {
    return switch (o) {
        case Integer i when i < 0 -> "negative";
        case Integer i when i == 0 -> "zero";
        case Integer i -> "positive: " + i;
        case null, default -> "other";
    };
}

6. Using Record Patterns (Java 21+)

FormExample
FlatPoint(int x, int y)
NestedLine(Point(int x1, int y1), Point(int x2, int y2))
Var inferencePoint(var x, var y)

7. Understanding Pattern Dominance

RuleEffect
Subtype before supertypeCompile error if reversed
Unguarded before guardedSame dominance check
null labelCannot be combined with type pattern unless null, default

8. Using Null Patterns

FormBehavior
No null labelSwitch throws NPE on null
case null ->Explicit null branch
case null, default ->Combined

9. Understanding Exhaustiveness in Switch

TypeExhaustive Required?
Switch expressionYes
Switch statement (arrow)Yes if uses patterns
Sealed typePermitted subtypes covered
EnumAll constants covered

10. Combining Multiple Patterns

CombinatorUse
Commacase A, B -> share branch
NestedRecord patterns nest
GuardRefine match further

11. Using Deconstruction Patterns

PatternEffect
Record patternBinds each component
var in patternInfers component type
Nested recordDeep destructure
Note: Deconstruction patterns for arbitrary classes are a preview feature in newer JDKs.