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

Answer:

Yes. The variable that follows the reserved word this is an instance variable (part of "this" object).


Review: for Loops

Here is a for loop:

{
    int sum = 0;

    for ( int count = 0;  count < 10; count++ )
    {
      System.out.print( count + " " );
      sum = sum+count;
    }
}

Scope Rule: a variable declared in a for statement can only be used in that statement and the body of the loop. The scope of count is only the loop body.

The following is NOT correct:

{
    int sum = 0;

    for ( int count = 0;  count < 10; count++ )  
    {
      System.out.print( count + " " );
      sum = sum+count;
    }

    // NOT part of the loop body
    System.out.println( 
      "\nAfter the loop count is: " + count );  
      
}

Since the println() statement is not part of the loop body, count cannot be used here. The compiler will complain that it "cannot find the symbol: count" when it sees this count. This can be a baffling error message if you forget the scope rule.

However, sum is declared outside of the for loop, so its scope starts with its declaration and continued to the end of the block.


QUESTION 12:

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

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