Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does x =new int[2]; work in this java code?

Tags:

java

arrays

Analyze the following code:

class Test {

    public static void main(String[] args) {
        int[] x = {1, 2, 3, 4};
        int[] y = x;

        x = new int[2];
        for (int i = 0; i < y.length; i++) {
            System.out.print(y[i] + " ");
        }
    }
}
  • A. The program displays 1 2 3 4
  • B. The program displays 0 0
  • C. The program displays 0 0 3 4
  • D. The program displays 0 0 0 0

The answer for the following code is A. But why the answer is not B ?

like image 686
Ratnajothy Avatar asked Dec 25 '15 11:12

Ratnajothy


3 Answers

Let's assume that {1, 2, 3, 4} has memory address M.

When assigning x to {1, 2, 3, 4}, you're assigning a reference to the memory address of {1, 2, 3, 4}, i.e. x will point to M.

When assigning y = x, then y will refer M.

After that, you're changing the reference where x points to, let's say it's N.

So, when printing, y points to M (which is the address of {1, 2, 3, 4}), but x holds reference to N (which is new int[2]). And here comes the difference.

like image 111
Konstantin Yovkov Avatar answered Sep 30 '22 21:09

Konstantin Yovkov


To give you a more clear explanation:

int[] x = {1, 2, 3, 4};       // step 1

enter image description here


int[] y = x;    // step 2

enter image description here


 x = new int[2];        // step 3

enter image description here


In the third step, when the x changes, y is not affected because you are changing the reference of x, not the address of the array. So it doesn't affect the value of y.

like image 23
singhakash Avatar answered Sep 30 '22 19:09

singhakash


Because int[] y = x; the array y will have some variables like this: {1,2,3,4}.

This line x = new int[2]; will creating a different space for x pointing to it.

So the result will be {1,2,3,4} of the array y

like image 21
Khuong Avatar answered Sep 30 '22 20:09

Khuong