For questions 21 - 23, use the following class definition:
public class Swapper
{
private int x;
private String y;
public int z;
public Swapper(int a, String b, int c)
{
x = a;
y = b;
z = c;
}
public String swap( )
{
int temp = x;
x = z;
z = temp;
return y;
}
public String toString( )
{
if (x < z) return y;
else return "" + x + z;
}
}
21) If the instruction Swapper s = new Swapper(0, "hello", 0); is executed followed by s.toString( ); what value is
returned from s.toString( )?
a) "hello"
b) "hello00"
c) "00"
d) "0"
e) 0
Answer: c. Explanation: The toString method compares x and z, and if x < y it returns the String y. In this case, x ==z, so the else clause is executed, and the String of "" + x + z is returned. This is the String "00".
22) Which of the following criticisms is valid about the Swapper class?
a) The instance data x is visible outside of Swapper
b) The instance data y is visible outside of Swapper
c) The instance data z is visible outside of Swapper
d) All 3 instance data are visible outside of Swapper
e) None of the methods are visible outside of Swapper
Answer: c. Explanation: We would expect none of the instance data to be visible outside of the class, so they should all be declared as “private” whereas we would expect the methods that make up the interface to be visible outside of the class, so they should all be declared as “public”. We see that z is declared “public” instead of “private”.
23) If we have Swapper r = new Swapper (5, "no", 10); then r.swap( ); returns which of the following?
a) nothing
b) "no"
c) "no510"
d) "510"
e) "15"
Answer: b. Explanation: The swap method swaps the values of x and z (thus x becomes 10 and z becomes 5) and returns the value of y, which is “no” for r.