Why does the following code work how does it use reference types rather than primitive types?
int[] a = new int[5]; int[] b = a; a[0] = 1; b[0] = 2; a[1] = 1; b[1] = 3; System.out.println(a[0]); System.out.println(b[0]); System.out.println(a[1]); System.out.println(b[1]);
And the result: 2 2 3 3 rather than 1 2 1 3
The contents of the int array may not be references, but the int [] variables are . By setting b = a , you copy the link, and two arrays point to the same piece of memory.
b = a
I describe what you are doing here:
int[] a = new int[5];
int[] b = a;
you are not creating a new instance of int[] b = a
int[] b = a
if you need a new instance (and the expected result) add clone() : int[] b = a.clone()good luck
clone()
int[] b = a.clone()
Both a and b point to () the same array. Changing the value in a or b will change the same value for another.
a
b