Pattern Matching with Logical Operators
You'll learn how pattern variables behave when combined with && and || operators, and when they're actually safe to use.
When you combine pattern matching with logical operators, Java carefully tracks whether the pattern variable is definitely assigned in each code path.
Pattern Variables with AND (&&)
When you use &&, the pattern variable is only available if both the pattern match succeeds and the additional condition is true:
if (obj instanceof String s && s.length() > 5) {
System.out.println(s.toUpperCase()); // ✓ s is available here
}
// s is NOT available here
The pattern variable s flows through because && short-circuits: if the instanceof fails, the second part never executes. If we reach the second condition, the pattern match succeeded and s exists.
Pattern Variables with OR (||)
With ||, things get trickier. The pattern variable is not available in the true branch when using ||:
if (obj instanceof String s || someOtherCondition) {
// s is NOT available here!
// Why? If someOtherCondition is true, s might not exist
}
However, in the false branch (after negation), the pattern variable can be available:
if (!(obj instanceof String s)) {
// s is NOT available here
} else {
System.out.println(s); // ✓ s is available in else block
}
Think of It Like a Guarantee
Pattern variable availability follows definite assignment: the compiler only lets you use the variable where it's guaranteed to exist. With &&, success on the left guarantees the variable exists when evaluating the right. With ||, there's no such guarantee in the success path.
Key Takeaway: Pattern variables work with && because short-circuit logic guarantees their existence; with ||, they're unavailable in the true branch because the match might not have occurred.