2,408 views

Given the array of integers ‘array’ shown below:

 13 7 27 2 18 33 9 11 22 8

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. 20:20
2. 18:18
3. 18:20
4. 20:18

for (int k = 0; k < 10; k ++)

p[k] = array [k];

in this loop we are copying all the values from the array to the array P

now

Q=p

Q is pointing P

now p[4]=20

but Q contains the old P array where in 4 th index i.e Q[4] is is also 20(as the location is updated by previous P )

Note: here pointer is involved , so the location is being update ,so Q is getting 20 here .

but  question is about array[4] which was  initial array ,so value 18

for (int k = 0; k < 10; k ++)

p[k] = array [k];

in this loop we are copying all the values from the array to the array P

now

Q=p

Q is pointing P

now p[4]=20

but Q contains the old P array where in 4 th index i.e Q[4] is is also 20(as the location is updated by previous P )

Note: here pointer is involved , so the location is being update ,so Q is getting 20 here .

but question is about array[4] which was also 18

for ( int k=0; k<10; k++)
p[k]= array [k];

The elements of "array" are copied to "p" using above statements.

q=p;

Memory location of "p" is assigned to "q" using above statement.

p[4]=20;

Memory location of p[4] now equals 20. So, q[4] = p[4] = 20

array[4] = 18

So,

System.out.println(array[4]+":"+q[4]);

prints 18:20