Java Reference
In-Depth Information
When Java encounters the inner for loop, it will complain that the variable i has
already been declared within this scope. You can't declare the same variable twice
within the same scope. You have to come up with two different names to distinguish
between them, just as when there are two Carls in the same family they tend to be
called “Carl Junior” and “Carl Senior” to avoid any potential confusion.
A control variable that is used in a for loop doesn't have to be declared in the ini-
tialization part of the loop. You can separate the declaration of the for loop control
variable from the initialization of the variable, as in the following code:
int i;
for (i = 1; i <= 5; i++) {
System.out.println(i + " squared = " + (i * i));
}
Doing so extends the variable's scope to the end of the enclosing set of curly
braces. One advantage of this approach is that it enables you to refer to the final value
of the control variable after the loop. Normally you wouldn't be able to do this,
because the control variable's scope would be limited to the loop itself. However,
declaring the control variable outside the loop is a dangerous practice, and it provides
a good example of the problems you can encounter when you don't localize vari-
ables. Consider the following code, for example:
int i;
for (i = 1; i <= 5; i++) {
for (i = 1; i <= 10; i++) {
System.out.println("hi there.");
}
}
As noted earlier, you shouldn't use the same control variable when you have
nested loops. But unlike the previous example, this code compiles, because here the
variable declaration is outside the outer for loop. So, instead of getting a helpful
error message from the Java compiler, you get a program with a bug in it. You'd think
from reading these loops that the code will produce 50 lines of output, but it actually
produces just 10 lines of output. The inner loop increments the variable i until it
becomes 11 , and that causes the outer loop to terminate after just one iteration. It can
be even worse if you reverse the order of these loops:
int i;
for (i = 1; i <= 10; i++) {
for (i = 1; i <= 5; i++) {
System.out.println("hi there.");
}
}
This code has an infinite loop.
 
Search WWH ::




Custom Search