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] + " ");
}
}
}
The answer for the following code is A. But why the answer is not B ?
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.
To give you a more clear explanation:
int[] x = {1, 2, 3, 4}; // step 1

int[] y = x; // step 2

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

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.
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
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