ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
// static method of the main class:
static void swap(int[] a, int[] b) {
    int[] t = a; a = b; b = t;
    a[0] = 100;
}
// in main:
int[] x = {1}, y = {2};
swap(x, y);
System.out.print(x[0] + " " + y[0]);
  1. A. 100 2
  2. B. 1 100
  3. C. 2 1
  4. D. 100 1

Correct answer: B. 1 100

Java passes references by value: swapping the parameters does not affect x and y. After the swap, parameter a refers to y's array, so a[0] = 100 modifies y.

More OOP with C++ and Java questions

Exams that ask this topic