Multiple choice technology

Consider this class example: class MyPoint { void myMethod() { int x, y; x = 5; y = 3; System.out.print( " ( " + x + ", " + y + " ) " ); switchCoords( x, y ); System.out.print( " ( " + x + ", " + y + " ) " ); } void switchCoords( int x, int y ) { int temp; temp = x; x = y; y = temp; System.out.print( " ( " + x + ", " + y + " ) " ); }}What is printed to standard output if myMethod() is executed?

  1. (5, 3) (5, 3) (5, 3)

  2. (5, 3) (3, 5) (5, 3)

  3. (5, 3) (3, 5) (3, 5)

  4. (3, 3) (3, 5) (3, 5)

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

Java passes primitive parameters by value, so switchCoords receives copies of x and y (values 5 and 3). Inside switchCoords, the swap changes only these local copies: temp=5, x becomes 3, y becomes 5, printing "(3, 5)". After the method returns, myMethod's original x and y remain unchanged at 5 and 3, so it prints "(5, 3)".

AI explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) (5, 3) (5, 3) (5, 3) - This option is incorrect because it suggests that the coordinates (x, y) remain unchanged after calling the switchCoords() method. However, the switchCoords() method swaps the values of x and y, so the coordinates should change.

Option B) (5, 3) (3, 5) (5, 3) - This option is incorrect because it suggests that the coordinates (x, y) change to (3, 5) after calling the switchCoords() method, but then revert back to (5, 3) afterward. However, the switchCoords() method swaps the values of x and y, so the coordinates should remain changed to (3, 5) after the method call.

Option C) (5, 3) (3, 5) (3, 5) - This option is correct because it correctly shows that the coordinates (x, y) change to (3, 5) after calling the switchCoords() method. The switchCoords() method swaps the values of x and y, so the coordinates should be (3, 5) after the method call.

Option D) (3, 3) (3, 5) (3, 5) - This option is incorrect because it suggests that the initial coordinates are (3, 3), which is not the case. The initial coordinates are (5, 3). The switchCoords() method only swaps the values of x and y, so the x-coordinate should change to 3, but the y-coordinate should remain 5.

The correct answer is Option C. This option is correct because it correctly shows that the coordinates (x, y) change to (3, 5) after calling the switchCoords() method.