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

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 to the following code: A. But why the answer is not B?

+4
source share
5 answers

Suppose it {1, 2, 3, 4}has a memory address M.

When assigned x, {1, 2, 3, 4}you assign a link to the memory address {1, 2, 3, 4}, i.e. xwill point to M.

Upon appointment y = x, ywill be referenced M.

After that, you change the link that x, say, points to N.

, y M ( {1, 2, 3, 4}), x N ( new int[2]). .

+9

:

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


, x, y , x, . , y.

+4

int[] y = x; y , : {1,2,3,4}.

x = new int[2]; x, .

, {1,2,3,4} y

+1

A. :

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

, x y , 4.

x = new int[2];

Now we have changed the value of x, but we have not changed the value of y.

So now x has a length of 2, which is {0, 0}, and y still has a length of 4, which is {1, 2, 3, 4}, and here comes the difference ...

for (int i = 0; i < y.length; i++)

In the line above, we already know that y.length = 4 , so I am <4 .

System.out.print(y[i] + " ");

The above line will now output an array of y values โ€‹โ€‹respectively, which are:

1

2

3

4

+1
source

Since you are assigning x to y without referring x to y.

+1
source

Source: https://habr.com/ru/post/1621701/


All Articles