public static void main(String[]args) {
int[] x = {1, 2, 3, 4};
int[] y ;
y = x;
x[1] = 11;
x = new int[2];
x[0]=99;
for (int i = 0; i < y.length; i++)
System.out.print(y[i] + " ");
System.out.println("");
for (int i = 0; i < x.length; i++)
System.out.print(x[i] + " ");
}
answer is
1 11 3 4
99 0
My question is I thought when you assign two arrays, they share the same changes since they are objects... like when I set x[1] = 11;
it changed the value of y
, so shouldn't y still be identical to x after changing it to a 2-sized array, or since I am changing the size they no longer point to the same address?
int[] x = {1, 2, 3, 4};
{1, 2, 3, 4}
is allocated as an array. A reference to it is assigned to x
.
int[] y ;
y = x;
A reference to that same array is assigned to y
as well.
x[1] = 11;
The array that both x
and y
refer to is now {1, 11, 3, 4}
.
x = new int[2];
A new array is allocated, due to Java semantics, as {0, 0}
. A reference to it is assigned to x
. Now x
and y
refer to two different arrays. There is no resizing being done.
x[0]=99;
The array referred to by x
is changed, and now contains {99, 0}
. This has nothing to do with the array y
refers to, which is still happily {1, 11, 3, 4}
.
x = new int[2];
This line creates a new array with a length of 2, and then makes x
point to that new array. At this point, the original array is only referenced by y
.
x[0] = 99;
This line assigns the 0th element in that new array to 99, and therefore the original array is left unchanged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With