Sub topic 5
Where the binding variable is in scope
This chapter assumes you know basic Java syntax, the boolean operators &&, || and !, and how a type pattern such as o instanceof String s declares a binding variable. Here you learn exactly where the compiler lets you use that variable.
Scope follows the program flow
A local variable normally lives in the block where you declare it. A binding variable does not. It is in scope only where the compiler can prove the pattern matched. This is called flow scoping: the scope follows how the program can run, not how the braces are nested.
Take the simplest case:
static String describe(Object o) {
if (o instanceof String s) {
return "string of length " + s.length();
} else {
// s is NOT in scope here: the pattern did not match.
return "something else: " + o;
}
}The variable s is available in the then branch, because that branch runs only when the test is true. It is not available in the else branch, because that branch runs when the test is false and s was never assigned.
True sets and false sets
The compiler tracks two sets of binding variables for every boolean expression:
- The bindings that are definitely matched when the expression is true.
- The bindings that are definitely matched when the expression is false.
For o instanceof String s, the first set is {s} and the second is empty. Each operator combines these sets in a fixed way.
| Expression | Bindings available when it is true | Bindings available when it is false | Column | Column |
|---|---|---|---|---|
| `o instanceof String s` | `s` | none | ||
| `!(o instanceof String s)` | none | `s` | ||
| `a && b` | those of `a` plus those of `b` | none | ||
| `a \ | \ | b` | none | those of `a` plus those of `b` |
The operators also make bindings available to the operand that runs after the first one:
- In
a && b, the bindings that are true foraare in scope inb. The right side runs only whenawas true. - In
a || b, the bindings that are false foraare in scope inb. The right side runs only whenawas false. - In
a ? b : c, the true bindings ofaare in scope inb. The false bindings ofaare in scope inc.
Using && and the conditional operator
The && rule is the one you will use most. Because the right operand runs only if the left one was true, you can use the binding at once:
static boolean isLongString(Object o) {
return o instanceof String s && s.length() > 10;
}The conditional operator works the same way for each of its two result expressions:
static int lengthOrMinusOne(Object o) {
return o instanceof String s ? s.length() : -1;
}Here s is in scope in the middle operand and not in the last one.
Negation flips the sets
Putting ! in front of a pattern swaps the two sets. The binding is then available when the whole expression is false. That makes || useful in a way that surprises many people:
static boolean notStringOrEmpty(Object o) {
return !(o instanceof String s) || s.isEmpty();
}This compiles. The right side of || runs only when the left side was false. The left side is false only when o instanceof String s is true, so s is matched there.
Compare it with the form that does not compile:
static boolean broken(Object o) {
// Does not compile: when the right side of || runs, the pattern did not match.
// return o instanceof String s || s.isEmpty();
return o instanceof String s && !s.isEmpty();
}Without the !, the right operand of || runs exactly when the pattern failed, so s has no value. The compiler rejects it.
Scope after an if statement
A binding can also stay in scope after the if statement ends. The rule is this: if the if statement has no else, and its body cannot complete normally, then the bindings that are true when the condition is false are in scope for the rest of the enclosing block. A body cannot complete normally when it always ends in return, throw, break or continue.
static int lengthOrMinusOne(Object o) {
if (!(o instanceof String s)) {
return -1;
}
// The body above always returns, so execution reaches this line
// only when the pattern matched.
return s.length();
}This is the early-exit guard. It keeps the main logic at the outer indentation level instead of nesting it inside an if.
If the body can complete normally, the scope does not extend, because execution can reach the next line with the pattern unmatched:
static int broken(Object o) {
if (!(o instanceof String s)) {
System.out.println("not a string"); // falls through
}
// return s.length(); // Does not compile: s may not be matched here.
return 0;
}You can combine this with || to put several checks in one guard:
static String shout(Object o) {
if (!(o instanceof String s) || s.isEmpty()) {
return "nothing to say";
}
return s.toUpperCase() + "!";
}The guard is false only when both operands are false, which means the pattern matched and the string is not empty. So s is in scope after the if.
The mirror-image rule applies too. If the if has an else branch that cannot complete normally and the then branch can, the true bindings are in scope after the statement.
Loops
A while statement follows similar rules. The true bindings of the condition are in scope in the loop body. The false bindings are in scope after the loop, as long as no break can exit the loop early. Here is a complete program that uses this:
import java.util.Iterator;
import java.util.List;
public class FirstString {
static String firstString(List<Object> items) {
Iterator<Object> it = items.iterator();
Object o = it.hasNext() ? it.next() : null;
while (!(o instanceof String s)) {
if (!it.hasNext()) {
return null;
}
o = it.next();
}
// The loop ends only when the condition is false, so s is matched.
return s;
}
public static void main(String[] args) {
System.out.println(firstString(List.of(1, 2.5, "found", "later"))); // found
System.out.println(firstString(List.of(1, 2))); // null
}
}Loops are the least common place to use this. The if guard covers most real code.
Name clashes and shadowing
A binding variable follows the usual rules for local variable names, with some extra care:
- You cannot declare a binding variable with the same name as a local variable or parameter that is already in scope. This is a compile-time error.
- If a field has the same name, the binding variable shadows it inside its scope. Use
this.nameto reach the field. - Two patterns in one expression cannot introduce the same name where both would be in scope together. For example,
a instanceof String s && b instanceof String sis an error. - The same name can be reused in separate branches where the scopes do not overlap, such as
if (a instanceof String s) {...} else if (a instanceof Integer s) {...}. Here the firstsis not in scope in theelsepart, so the second is legal. It is still easy to misread, so distinct names are usually clearer.
Checking your understanding of the rules
When you are unsure whether a binding is in scope at some point, ask one question: can execution reach this point without the pattern having matched? If the answer is yes for any path, the compiler rejects the use. If the answer is no for every path, the use is allowed.
Exercise
Does this method compile? If not, say which line fails and why. static int f(Object o) { if (o instanceof Integer n || n > 0) { return 1; } return 0; }
Show answer
It does not compile. In o instanceof Integer n || n > 0, the right side of || runs only when the left side was false, which means the pattern did not match. So n is not in scope on the right side. Using && instead (o instanceof Integer n && n > 0) fixes it.
Exercise
This method is meant to return the length of a string, or -1 for anything else. It fails to compile. Explain why, and give two different ways to fix it. static int g(Object o) { if (!(o instanceof String s)) { System.out.println("not a string"); } return s.length(); }
Show answer
The body of the if can complete normally, because it only prints. Execution can therefore reach s.length() with the pattern unmatched, so s is not in scope there. Fix 1: make the body end with return -1; so it cannot complete normally, which puts s in scope after the if. Fix 2: drop the negation and use if (o instanceof String s) { return s.length(); } return -1;.
Exercise
Why does return !(o instanceof String s) || s.isEmpty(); compile when return o instanceof String s || s.isEmpty(); does not?
Show answer
The ! swaps the bindings. In the first form, the left operand is false exactly when the pattern matched, and the right operand of || runs only when the left operand is false, so s is matched there. In the second form, the right operand runs when the left operand is false, which means the pattern failed, so s has no value.