Flow Scoping: Pattern Variables in Conditional Blocks
What You'll Learn
You'll learn how Java intelligently extends the scope of pattern variables based on control flow, making them available only when the compiler can guarantee the type test succeeded.
The Concept of Flow Scoping
When you use pattern matching with instanceof, Java creates a pattern variable that holds the casted value. But here's the clever part: this variable isn't available everywhere—only where the compiler knows the type test must have passed.
Think of it like a security checkpoint. The pattern variable is your "all-access pass," but you only get it in areas where Java can prove you've already passed through the checkpoint successfully.
How It Works in Conditionals
After a successful instanceof test in an if condition, the pattern variable is in scope throughout the entire if block:
Object obj = "Hello";
if (obj instanceof String s) {
// s is in scope here - test passed!
System.out.println(s.length());
System.out.println(s.toUpperCase());
// Can use s anywhere in this block
}
// s is NOT in scope here - test might have failed
The pattern variable s is available inside the if block because the compiler knows: "If we're executing this code, obj must be a String."
Flow-Based Logic
The scope extends based on control flow logic, not just block boundaries. If the if test fails and execution skips the block, the variable was never created—because the cast would have been invalid anyway.
This flow-aware scoping prevents errors: you literally cannot use the pattern variable where the type isn't guaranteed.
Key Takeaway: Pattern variables have "flow scope"—they're available only in code paths where the compiler can prove the instanceof test succeeded, preventing unsafe access to incorrectly-typed values.