Java Reference
In-Depth Information
words, this statement says, “Add to
sum
the value of
sum
plus
i
, then increment
i
.” Thus,
it is the same as this sequence of statements:
Declaring Loop Control Variables Inside the for Loop
Often the variable that controls a
for
loop is needed only for the purposes of the loop and
is not used elsewhere. When this is the case, it is possible to declare the variable inside
the initialization portion of the
for
. For example, the following program computes both the
summation and the factorial of the numbers 1 through 5. It declares its loop control variable
i
inside the
for
.
When you declare a variable inside a
for
loop, there is one important point to remember:
the scope of that variable ends when the
for
statement does. (That is, the scope of the vari-
able is limited to the
for
loop.) Outside the
for
loop, the variable will cease to exist. Thus,
in the preceding example,
i
is not accessible outside the
for
loop. If you need to use the
loop control variable elsewhere in your program, you will not be able to declare it inside
the
for
loop.
Before moving on, you might want to experiment with your own variations on the
for
loop. As you will find, it is a fascinating loop.