Consider the following swap method. If String x = "Hello" and String y = "Goodbye", then swap(x, y); results in which of the following?

Consider the following swap method.  If String x = "Hello" and String y = "Goodbye", then swap(x, y); results in which of the following?

public void swap(String a, String b)
{
                 String temp;
                 temp = a;
                 a = b;
                 b = temp;
}
a)       x is now "Goodbye" and y is now "Hello"
b)       x is now "Goodbye" and y is still "Goodbye", but (x != y)
c)       x is still "Hello" and y is now "Hello", but (x != y)
d)       x and y are now aliases
e)       x and y remain unchanged


Answer:  e.

Explanation:  When x and y are passed to swap, a and x become aliases and b and y become aliases.  The statement temp = a sets temp to be an alias of a and x.  The statement a = b sets a to be an alias of b and y, but does not alter x or temp.  Finally, b = temp sets b to be an alias of temp and y, but does not alter y.  Therefore, x and y remain the same.


Enhancing Classes

Learn More Multiple Choice Question :