go to previous page   go to home page   go to next page

Answer:

int sum = 0;
for ( int j = 0;  j < 8; j++ )
    sum = sum + j;

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

Yes. Here the println() statement is within the scope of sum.


Mystery of the Many Scopes

Examine the following program. What does it print?

class Mystery
{
  private int sum;
  
  public Mystery( int sum )
  {
    this.sum = sum;
  }
  
  public void increment( int inc )
  {
    sum = sum + inc;
    System.out.println("Mystery sum: " + sum );
  }
}

public class Tester
{
  public static void main ( String[] args)
  {
    int sum = 99;
    Mystery myst = new Mystery( 34 );
    myst.increment( 6 );
    System.out.println("sum: " + sum );
  } 
}

Notice that the identifier sum is used for three different things:

  1. The instance variable of a Mystery object.
  2. The parameter of the Mystery constructor.
  3. The local variable of the main() method.

QUESTION 13:

What is printed?


go to previous page   go to home page   go to next page