Scope in Loop Bodies
What you'll learn: How variables declared inside a loop behave — and why they vanish when the loop completes.
The Core Idea
When you declare a variable inside a loop body (whether for, while, or do-while), that variable is recreated on every single iteration and ceases to exist as soon as the loop finishes. The variable's scope is confined strictly to the curly braces {} of the loop body.
Think of it like a notebook you use only during a single class period. Each day (each iteration), you get a fresh notebook. When class ends (loop completes), that notebook is thrown away. You can't reference it from the hallway (outside the loop).
Why This Matters
for (int i = 0; i < 3; i++) {
int counter = 0; // declared inside loop
counter++;
System.out.println(counter); // prints 1 three times
}
// counter does not exist here!
Notice counter resets to 0 on every iteration because it's redeclared each time. After the loop, trying to use counter would cause a compile error — it's out of scope.
Contrast with variables declared before the loop:
int total = 0; // declared outside
for (int i = 0; i < 3; i++) {
total++; // accumulates across iterations
}
System.out.println(total); // prints 3
Here, total survives all iterations and remains accessible afterward because it was declared in the outer scope.
Practical Implications
- Declare loop-local variables (
int temp, etc.) inside the loop when they're only needed per iteration - Declare variables outside the loop if you need to accumulate values or access them after the loop ends
- Loop control variables (
iinfor (int i = ...)) are also scoped to the loop
Key Takeaway: Variables declared inside a loop body are recreated each iteration and cannot be accessed outside the loop; declare them outside if you need persistence or post-loop access.