Pattern Variables and Scope
You'll learn: How pattern variables introduced with instanceof are scoped, when they're definitely assigned, and how Java prevents shadowing conflicts.
Understanding Pattern Variable Scope
When you use pattern matching with instanceof, Java introduces a pattern variable—but this variable doesn't exist everywhere. Java carefully controls where you can use it based on program flow.
The pattern variable is only in scope where the type check guarantees success. Think of it like a flashlight that only illuminates safe areas: if the instanceof test passes, the pattern variable "lights up" in that region of code.
Flow Scoping Rules
if (obj instanceof String s) {
// ✓ s is in scope here (test passed)
System.out.println(s.length());
} else {
// ✗ s is NOT in scope here (test failed)
// System.out.println(s.length()); // Compile error!
}
// ✗ s is NOT in scope after the if-block
The variable s exists only inside the if branch where we know obj is a String.
Definite Assignment After &&
if (obj instanceof String s && s.length() > 5) {
// ✓ s is in scope in the second part of &&
System.out.println(s);
}
Java understands logical operators: after &&, the pattern variable is definitely assigned because the left side must have succeeded first.
Shadowing Prevention
Java prevents you from reusing names that would cause confusion:
String s = "hello";
if (obj instanceof String s) { // Compile error!
// Can't shadow the existing 's'
}
Key Takeaway: Pattern variables are scoped based on where the type test guarantees success (flow-sensitive scoping), they're definitely assigned after logical &&, and Java blocks shadowing to prevent naming conflicts.