Is the following code fragment correct?
int sum = 0; for ( int j = 0; j < 8; j++ ) sum = sum + j; System.out.println( "The sum is: " + sum );
Yes. The variable sum
is declared outside of the for
statement and can be used inside and outside of the loop body.
The variable j
is declared inside of the for
statement and can be used only in the body of the loop.
The scope of a variable is the span of statements where it can be used.
The scope of a variable declared as part of a for
statement is
that statement and its loop body.
Another way to say this is:
A loop control variable declared as part of afor
statement can only be "seen" by thefor
statement and the statements of that loop body.