More about the For Statement

This chapter discusses the 'for' loop in greater detail, as well as the scope of variables in the 'for' loop.

3. Scope


Answer:

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.

Scope

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 for statement can only be "seen" by the for statement and the statements in that loop body.


Question 3:

Is the following code correct?

public class BigScope
{
  public static void main ( String[] args )
  {
    int sum = 0;

    for ( int j = 0;  j < 80; j++ )
    {
      if ( j % 7 != 0 )
        sum  = sum + j;
      else
        System.out.println( "Not added to sum: "  + j );
    }

    System.out.println( "The final sum is: " + sum ); 

  }
}