Sub topic 2
Where the Binding Variable Is in Scope
Assume you know basic Java classes, inheritance, casts, Boolean operators, and instanceof. A binding variable is the variable declared by a type pattern. Its scope depends on whether Java can prove that the pattern matched.
Where the binding variable is in scope
public class ScopeDemo {
static void printLength(Object value) {
if (value instanceof String text) {
System.out.println(text.length());
}
// text is not in scope here.
}
public static void main(String[] args) {
printLength("hello");
}
}Here, text has type String. It exists only where the compiler knows that value is a String. The variable is not available after the if statement because the pattern might not have matched.
Adding conditions with `&&`
The right side of && runs only when the left side is true. Therefore, the binding variable is available on the right side.
static boolean isLongString(Object value) {
return value instanceof String text && text.length() > 10;
}The variable is also available inside the body of an if whose condition contains this expression.
By contrast, the right side of || can run when the pattern did not match. This does not compile:
// value instanceof String text || text.isEmpty()Java cannot guarantee that text exists on the right side.
Negation and early returns
With !, a matched variable is not available inside the branch where the negated condition is true. An early return can establish the opposite fact for code that follows.
static int lengthOrMinusOne(Object value) {
if (!(value instanceof String text)) {
return -1;
}
return text.length();
}If execution reaches the last line, the failed case has already returned. The compiler can therefore prove that text is a matched String.
How null behaves
instanceof is false when its left operand is null. A type pattern follows the same rule, so it does not bind a variable for null.
public static void main(String[] args) {
Object value = null;
System.out.println(value instanceof String text); // false
}Exercise
Why can text be used after the early return in lengthOrMinusOne, but not after a normal if statement?
Show answer
The early return removes the path where the pattern failed, so every remaining path has a successfully matched String.