Sub topic 5
Understand loop variable scope
A loop often uses a variable to track its progress. But where can you use that variable? The answer depends on its scope.
Scope is the part of a program where a name can be used. In Java, a loop variable may be available inside the loop but not after it. Knowing its scope helps you decide where to declare it and how long to keep it available.
This chapter assumes you have seen Java variables, blocks, conditions, and basic loops. We will focus on where loop variables can be used, rather than on how each kind of loop works.
Start with blocks and local variables
A block is a group of statements inside braces, { and }. A method body is a block. A loop body can also be a block.
A local variable is a variable declared inside a method, or inside a block within a method. A declaration introduces a variable by giving its type and name. For example, int limit = 3; declares a local variable named limit.
A local variable declared in a block can be used after its declaration, within that block. It is not available outside that block.
Look at this complete program:
public class Main {
public static void main(String[] args) {
int limit = 3;
for (int i = 0; i < limit; i++) {
int doubled = i * 2;
System.out.println("i: " + i + ", doubled: " + doubled);
}
System.out.println("Limit: " + limit);
}
}Save it as Main.java, then compile and run it:
javac Main.java
java MainThe output is:
i: 0, doubled: 0i: 1, doubled: 2i: 2, doubled: 4Limit: 3
The three variables have different scopes:
| Variable | Where it is declared | Where it can be used |
|---|---|---|
| `limit` | In the method block, before the loop | After its declaration in the method block, including inside the loop |
| `i` | In the `for` loop header | In the rest of the loop header and in the loop body |
| `doubled` | In the loop body block | After its declaration in that body block |
The header is the part of a for loop inside its parentheses. The body is the statement or block that runs when the loop condition is true.
The following diagram shows the scope regions in the example. It shows which regions are inside others; it does not show the order in which statements run.
An inner region can use a name from an enclosing region. An enclosing region cannot use a name that exists only in an inner region.
For example, the loop body can use limit. The final print statement can also use limit. But that final statement cannot use i or doubled, because it is outside their scopes.
Scope of a variable declared in a for header
A basic for header has three parts: a starting part, a condition, and an update. In the previous example:
int i = 0declaresiand gives it a starting value.i < limitis the condition, a true-or-false test.i++is the update; it increasesiby one.
When you declare i in the starting part, its scope covers the rest of the loop header and the loop body. That is why both the condition and the update can use i.
Its scope ends with the for statement. If you try to print i on the line after that loop, Java reports an error when you compile the program.
The compiler is the tool that checks Java code and translates it so it can run. A scope error means the compiler cannot use the name at that location.
A body variable is not a header variable
The reverse also matters. A variable declared inside the body is not available in the header.
In the first program, doubled is declared inside the braces. You can print it later in that body, but you cannot use it in the loop condition or update. Those parts of the header are outside the body block.
Also, a variable cannot be used before its declaration in the block. If the print statement that uses doubled came before the declaration, the program would not compile.
Declare a variable outside the loop when you need it later
Sometimes you want to use a loop variable after the loop ends. In that case, declare it in an enclosing block.
Replace the contents of Main.java with this program and run it:
public class Main {
public static void main(String[] args) {
int index = 0;
for (; index < 3; index++) {
System.out.println("During loop: " + index);
}
System.out.println("After loop: " + index);
}
}The output is:
During loop: 0During loop: 1During loop: 2After loop: 3
Here, index is declared in the method block. The for header does not declare it again. The starting part of the header is empty because the program has already given index a value.
The loop can use index because the loop is inside the variable’s scope. The final print statement can use it for the same reason.
When the loop finishes, index is 3. The update increased it after the last body run. Then the condition became false.
If the starting value had been 3 or more, the body would not have run. The final print statement could still use index, because its scope does not depend on whether the body runs.
Choose the smaller useful scope
If you do not need a variable after the loop, declaring it in the header is often clearer:
public class Main {
public static void main(String[] args) {
for (int index = 0; index < 3; index++) {
System.out.println(index);
}
}
}This tells a reader that index is for the loop. It also prevents later code from changing or using it by mistake.
Choose an outer declaration when later code needs the value. Choose a loop-header declaration when the value is only needed for that loop.
Scope in while and do-while loops
The same block rules apply to while and do-while loops. A variable declared inside a body block is available only inside that block. It is not available in the loop condition outside the block.
This program uses a variable declared before a while loop:
public class Main {
public static void main(String[] args) {
int step = 0;
while (step < 2) {
int nextStep = step + 1;
System.out.println("Next step: " + nextStep);
step = nextStep;
}
System.out.println("Final step: " + step);
}
}The output is:
Next step: 1Next step: 2Final step: 2
The condition can use step because step was declared in the enclosing method block. The body can use both step and nextStep.
The final print statement can use step, but not nextStep. The scope of nextStep ends at the closing brace of the loop body.
A do-while loop has the same scope rule. Its condition comes after the body, but it is still outside the body block:
public class Main {
public static void main(String[] args) {
int attempt = 0;
do {
int nextAttempt = attempt + 1;
attempt = nextAttempt;
System.out.println("Attempt: " + attempt);
} while (attempt < 3);
System.out.println("Attempts made: " + attempt);
}
}The condition uses attempt, which was declared outside the body. It cannot use nextAttempt, even though the condition appears after the closing brace. A name being earlier in the file does not mean it is still in scope.
A body variable starts fresh on each iteration
An iteration is one run of a loop body. When a declaration inside the body runs on each iteration, that body variable starts with the value given by its declaration each time.
Compare the two totals in this program:
public class Main {
public static void main(String[] args) {
int total = 0;
for (int i = 1; i <= 3; i++) {
int oneTimeTotal = 0;
oneTimeTotal = oneTimeTotal + i;
total = total + i;
System.out.println("i: " + i
+ ", one-time total: " + oneTimeTotal
+ ", total: " + total);
}
System.out.println("Final total: " + total);
}
}The output is:
i: 1, one-time total: 1, total: 1i: 2, one-time total: 2, total: 3i: 3, one-time total: 3, total: 6Final total: 6
Here is the same work in a table:
| Iteration | Value of `i` | `oneTimeTotal` after adding `i` | `total` after adding `i` |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 3 |
| 3 | 3 | 3 | 6 |
oneTimeTotal starts at 0 each time the body runs. It does not keep the value from the previous iteration.
total is declared and given a value before the loop. The body changes that same variable on each iteration, so its value can grow. It is also available for the final print statement.
This distinction is useful when you need a running total: declare the total outside the loop, then update it inside.
Reuse names in separate scopes
You can use the same local variable name in two separate loops when the scopes do not overlap. For example:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
System.out.println("First loop: " + i);
}
for (int i = 0; i < 3; i++) {
System.out.println("Second loop: " + i);
}
}
}The first loop’s i is out of scope before the second loop declares its own i. Each loop has a separate variable.
But you cannot declare another local variable with the same name while the first local variable is still in scope. This rule also applies in an inner block. For example, if you declare int i = 0; in the method block before a loop, do not also declare int i in that loop’s header.
You have two choices:
- Use the existing variable in the loop header without declaring it again.
- Give the new variable a different name, if it has a different job.
The same naming rule applies to a method parameter. A parameter is a named value that a method receives. You cannot declare a local variable with the same name while that parameter is in scope.
Scope and starting values are different
A variable being in scope means its name can be used at that location. It does not always mean the variable has been given a value.
Java requires a local variable to be assigned a value before its value is read. For example, declaring int total; introduces the name, but it does not give total a starting value. A statement that tries to read total before an assignment will not compile.
This matters with loops. If you plan to print a result after a loop, give it a suitable starting value before the loop. A while or for body may run zero times, so an assignment that happens only inside the body may not happen at all.
In the earlier total example, int total = 0; both declares total and gives it a value before the loop. The final print statement can then use it.
Check scope when an error occurs
When a variable causes a compile error, trace its scope in this order:
- Find the declaration. Check the spelling and the variable’s type.
- Find the block or loop statement that contains the declaration.
- Find the point where you want to use the name. Is it inside the right region and after the declaration?
- If the variable is declared in a loop body, check whether you are trying to use it in the header or after the body.
- If the name is in scope, check that the variable has been assigned a value before you read it.
- If Java reports a duplicate local variable, check whether an earlier declaration with that name is still in scope.
Then decide what the program needs. If a value must be used after the loop, declare it in an enclosing block. If it is useful only for one body run, keep it in the body. A variable placed in the right scope is easier to find and harder to use by accident.
Exercises
Exercise
In the first program, can the final print statement use limit, i, and doubled?
Show answer
It can use limit. It cannot use i, whose scope ends with the for statement, or doubled, whose scope ends with the loop body.
Exercise
In the program that declares index before the for loop, what is index after the loop? What would it be if it started at 3 instead?
Show answer
It is 3 after the loop. If it started at 3, the body would not run and index would still be 3.
Exercise
Why does oneTimeTotal not become 6 in the running-total example?
Show answer
Its declaration is inside the loop body, so it starts at 0 on each iteration. The outer total keeps its value between iterations and becomes 6.
Exercise
A do-while body declares nextAttempt, but the condition needs that value. What scope change would make the name available to the condition?
Show answer
Declare nextAttempt in an enclosing block before the loop and assign it a suitable value there or in the body before the condition reads it.
Exercise
Can two separate for loops in the same method each declare a local variable named i in their headers?
Show answer
Yes, if the first loop ends before the second begins and no other local variable or parameter named i is still in scope.