Parameters, Local Variables, and Overloading
13. Mystery of the Many Scopes
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:
- The instance variable of a
Mystery
object. - The parameter of the
Mystery
constructor. - The local variable of the
main()
method.
Question 13:
What is printed?