Java Reference
In-Depth Information
Infinite Loop
A loop that never terminates.
This loop is infinite because no matter what the outer loop does to the variable i ,
the inner loop always sets it back to 1 and iterates until it becomes 6 . The outer loop
then increments the variable to 7 and finds that 7 is less than or equal to 10 , so it
always goes back to the inner loop, which once again sets the variable back to 1 and
iterates up to 6 . This process goes on indefinitely. These are the kinds of interference
problems you can get when you fail to localize variables.
Common Programming Error
Referring to the Wrong Loop Variable
The following code is intended to print a triangle of stars. However, it has a sub-
tle bug that causes it to print stars infinitely:
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= i; i++){
System.out.print("*");
}
System.out.println();
}
The problem is in the second line, in the inner for loop header's update state-
ment. The programmer meant to write j++ but instead accidentally wrote i++ . A
trace of the code is shown in Table 2.7.
Table 2.7
Trace of Nested for Loop
Step
Code
Description
initialization
variable i is created and initialized to 1
int i = 1;
initialization
variable j is created and initialized to 1
int j = 1;
test
true because 1 <= 1 , so we enter the inner loop
j <= i
body
execute the print with j equal to 1
{...}
update
increment i , which becomes 2
i++
test
true because 1 <= 2 , so we enter the inner loop
j <= i
body
execute the print with j equal to 1
{...}
update
increment i , which becomes 3
i++
...
...
...
The variable j should be increasing, but instead i is increasing. The effect of
this mistake is that the variable j is never incremented in the inner loop, and
therefore the test of j <= i never fails, so the inner loop doesn't terminate.
Continued on next page
 
 
Search WWH ::




Custom Search