Scope in loops, traced like a compiler¶
โ Java 17 ยท Managing Variable Scope ยท 2/3
Braces define scope. Loops follow the same rule, with a detail that catches many people: the loop counter.
The loop variable belongs to the loop¶
public void loadEpisodes(int count) {
for (int i = 0; i < count; i++) {
String title = "Ep-" + i;
System.out.println(title);
}
System.out.println(i); // โ i is out of scope
System.out.println(title); // โ title too
}
iis declared in theforheader, so its scope is the loop, not the method.titleis declared in the loop body: a freshtitleis created on each iteration, and none survives the loop.
while loops work the same way for variables declared in their body. And var changes nothing: a var declared in a block dies with that block.
If you need a value after the loop, declare the variable before the loop.
Tracing scope line by line¶
The safest way to reason about scope is to note where each variable is born and where it dies:
1 public void recommend(boolean premium) {
2 int suggestions = 5;
3 while (suggestions > 0) {
4 int watched = 1;
5 if (premium) {
6 var bonus = 2;
7 watched += bonus;
8 }
9 suggestions -= watched;
10 }
11 System.out.println(suggestions);
12 }
| Variable | Lives from โ until |
|---|---|
premium |
line 1 โ end of the method |
suggestions |
line 2 โ end of the method |
watched |
line 4 โ line 10, recreated on each iteration |
bonus |
line 6 โ line 8, recreated each time the if runs |
At line 11, only premium and suggestions exist. Using watched or bonus there would not compile.
Declared but unused is fine¶
int episodes = 10;
for (int i = 0; i < 2; i++) {
int bonus = i * 3;
}
System.out.println(episodes); // โ
prints 10
bonus goes out of scope after the loop, but nothing tries to use it there, so the code compiles. Scope errors happen only when a variable is used outside its region.
The lab puts all three levels โ field, method and loop โ in one runnable class.