Loop Variable Scope in for Loops
What you'll learn: You'll discover that variables declared inside a for loop's header are only available within that loop—and vanish afterward.
The Key Idea
When you declare a variable directly in the initialization section of a for loop (the first part inside the parentheses), that variable exists only for the duration of the loop. Once the loop finishes, the variable disappears—you can't access it anymore.
Think of it like a movie theater ticket: it grants you access while the film is playing, but once the credits roll, the ticket is worthless. Your loop variable works the same way—it's valid inside the loop, but ceases to exist outside it.
How It Works in Practice
for (int i = 0; i < 5; i++) {
System.out.println(i); // Works fine - i exists here
}
// i no longer exists here
System.out.println(i); // Compiler error: cannot find symbol 'i'
The variable i is scoped to the loop. It's born when the loop starts and dies when the loop ends.
Why This Matters
This scoping rule prevents accidental misuse of loop variables and keeps your code clean:
for (int i = 0; i < 3; i++) {
// first loop using i
}
for (int i = 0; i < 5; i++) {
// completely separate i - no conflict!
}
You can reuse the same variable name i in different loops because each one creates its own independent variable.
Contrast with Pre-Declaration
If you declare the variable before the loop, it survives afterward:
int i;
for (i = 0; i < 5; i++) {
// loop body
}
System.out.println(i); // Works! i still exists and equals 5
Key Takeaway: Variables declared in a for loop's header exist only within that loop's body—they're inaccessible before or after, keeping each loop's control variable isolated and preventing naming conflicts.