Scope

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

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 );

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 of that loop body.

QUESTION 3:

Is the following code correct?


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 ); 

  }
}