Pattern Matching in Complex Conditionals
What you'll learn: How to use pattern matching for instanceof in nested conditions, else-if chains, and understand how scope rules work when patterns get more complicated.
Beyond Simple Conditions
You've seen pattern matching work in straightforward if-statements, but real code often involves multiple checks, nested conditions, and else-if ladders. The good news? Pattern variables follow clear scope rules even in complex scenarios, making your code cleaner than traditional test-cast-use patterns.
Pattern Matching in else-if Chains
When you have multiple type checks in sequence, pattern variables are scoped to their specific branch:
if (obj instanceof String s) {
System.out.println("String length: " + s.length());
} else if (obj instanceof Integer i) {
System.out.println("Integer value: " + i);
} // s and i are both out of scope here
Each pattern variable only exists within its branch—no interference between them.
Nested Conditions
You can nest pattern matching inside other conditionals:
if (animal instanceof Dog d) {
if (d.getAge() > 10) {
System.out.println(d.getName() + " is a senior dog");
}
}
The pattern variable d is available throughout the outer if-block, including nested conditions inside it.
Combining with Logical Operators
Remember flow scoping from earlier? In complex expressions, the compiler tracks where pattern variables are definitely assigned:
if (obj instanceof String s && s.length() > 5) {
// s is in scope: we only reach here if instanceof succeeded
}
if (!(obj instanceof Integer i) || i > 0) {
// i is NOT available here—could be false because obj wasn't an Integer
}
The key is understanding when the compiler guarantees the pattern variable is assigned based on the logical flow.
Key Takeaway: Pattern matching works seamlessly in else-if chains and nested conditions, with pattern variables scoped to their branch; always think about the logical flow to understand where your pattern variables are accessible.