Sub topic 5
Understand loop variable scope
A variable is a named place that holds a value. In Java, a variable has a scope: the part of the program where you can use its name.
Scope matters in loops because a variable you create in a loop may not be available after the loop ends. Knowing where a variable belongs also helps you avoid changing it by mistake.
Find the scope of a loop variable
A block is a group of statements inside braces, { and }. The statements inside a loop’s braces form its body. Each time the body runs is an iteration.
In a basic for loop, the part in parentheses is the header. If you declare a variable there, you can use it in the rest of the header and in the loop body. You cannot use it after the loop.
To declare a variable is to give it a type and a name. For example, int i declares a variable named i that holds a whole number.
Try this complete program. Save it as LoopScopeDemo.java, then run javac LoopScopeDemo.java followed by java LoopScopeDemo.
public class LoopScopeDemo {
public static void main(String[] args) {
int total = 0;
for (int i = 0; i < 3; i++) {
int doubled = i * 2;
total = total + doubled;
System.out.println("i=" + i + ", doubled=" + doubled);
}
System.out.println("total=" + total);
}
}The program prints four lines: i=0, doubled=0, i=1, doubled=2, i=2, doubled=4, and total=6.
Here is where each variable can be used:
| Variable | Declared in | Where you can use it |
|---|---|---|
| `total` | The `main` method’s block | After its declaration, both inside and after the loop |
| `i` | The `for` header | In the rest of the header and in the loop body |
| `doubled` | The loop body | After its declaration, within the loop body |
A method is a named group of instructions. In this program, main is the method where the program starts.
Look inside and outside the loop
The loop starts with i equal to 0. The header can test i < 3 and update i with i++ because those parts are within the scope of i. The body can also use i to calculate doubled.
But if you add System.out.println(i); after the loop, Java reports an error. The name i is no longer in scope there.
The variable doubled has an even smaller scope. It is declared inside the body, so you can use it after its declaration in that body. You cannot use it in the loop header or after the loop. Each time the body runs, the statement declares doubled and gives it a value for that iteration.
The variable total is different. It is declared before the loop, in the surrounding block. The loop can update it, and the program can still print it after the loop. That lets the values added during different iterations build up to 6.
Keep a loop variable after the loop
Sometimes you need the loop variable after the loop finishes. In that case, declare it before the loop instead of in the header.
Save this program as AfterLoop.java, then compile and run it with javac AfterLoop.java and java AfterLoop.
public class AfterLoop {
public static void main(String[] args) {
int count = 0;
for (; count < 3; count++) {
System.out.println("In loop: " + count);
}
System.out.println("After loop: " + count);
}
}The first part of the for header is empty because count already exists. The loop prints 0, 1, and 2. After the last update, count is 3, so the condition is false and the loop ends. The final line prints After loop: 3.
The compiler is the tool that checks and translates Java code. If you declare count before the loop, do not also write int count in the loop header. The two declarations would have overlapping scopes, so the compiler would report an error.
Choose a useful scope
Declare a variable in the smallest scope that needs it.
- Put a variable in the
forheader when only that loop needs it. - Put a variable in the loop body when only that body needs it.
- Declare a variable before the loop when you also need it afterward.
A variable declared inside a smaller block is not available outside that block. The same idea applies to blocks used by other loop types: look at where the variable is declared and where its surrounding block ends.
You may use the same name for loop variables in two separate loops, as long as their scopes do not overlap. For example, one for loop can declare i, and a later for loop can declare a new i.
Exercise
In LoopScopeDemo, can the final print statement use doubled instead of total? Why?
Show answer
No. doubled is declared inside the loop body, so it is out of scope after the loop.
Exercise
A for loop declares int i = 0 in its header. You need to print i after the loop. What should you change?
Show answer
Declare int i = 0; before the loop. Leave the first part of the for header empty, and keep the condition and update in the header.