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
statement and can be used inside and outside of the loop body.
j is declared inside of the
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 a
forstatement can only be "seen" by the
forstatement and the statements of that loop body.