Given the array of integers ‘array’ shown below: What is the output of the…

2017

Given the array of integers ‘array’ shown below:

What is the output of the following JAVA statements?

int[] p = new int [10]; int[] q = new int [10]; for (int k=0; k< 10; k++) p[k]=array [k]; q=p; p[4]=20; System.out.println(array[4]+":"+q[4]);
  1. A.

    20 : 20

  2. B.

    18 : 18

  3. C.

    18 : 20

  4. D.

    20 : 18

Attempted by 64 students.

Show answer & explanation

Correct answer: C

Initial array values: 13, 7, 27, 2, 18, 33, 9, 11, 22, 8

Step-by-step reasoning:

  • p is created and each element is copied from the original array using p[k] = array[k]; so p is a separate array with the same values as the original.

  • q = p; makes q refer to the same array object as p (q and p are references to the same array).

  • p[4] = 20; changes the shared array referenced by p and q, so q[4] becomes 20 as well. The original array was not modified by this assignment, so its element at index 4 remains 18.

Final values: array[4] = 18, q[4] = 20

Output: 18:20

Explore the full course: Mppsc Assistant Professor