Java Reference
In-Depth Information
for (int i = 1; i <= n; i++)
{
. . .
}
// i no longer defined here
The scope of the variable extends to the end of the for loop. Therefore, i is no
longer defined after the loop ends. If you need to use the value of the variable
beyond the end of the loop, then you need to define it outside the loop. In this loop,
you don't need the value of i Ȍyou know it is n + 1 when the loop is finished.
(Actually, that is not quite trueȌit is possible to break out of a loop before its end;
see Advanced Topic 6.4 ). When you have two or more exit conditions, though, you
may still need the variable. For example, consider the loop
for (i = 1; balance < targetBalance && i <= n; i++)
{
. . .
}
You want the balance to reach the target, but you are willing to wait only a certain
number of years. If the balance doubles sooner, you may want to know the value of
i . Therefore, in this case, it is not appropriate to define the variable in the loop
header.
Note that the variables named i in the following pair of for loops are
independent:
for (int i = 1; i <= 10; i++)
System.out.println(i * i);
for (int i = 1; i <= 10; i++) // Declares a new variable i
System.out.println(i * i * i);
243
244
In the loop header, you can declare multiple variables, as long as they are of the
same type, and you can include multiple update expressions, separated by commas:
for (int i = 0, j = 10; i <= 10; i++, j--)
{
. . .
}
However, many people find it confusing if a for loop controls more than one
variable. I recommend that you not use this form of the for statement (see Quality
Search WWH ::




Custom Search