Reputation: 939
Why next code works like it uses 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 output is: 2 2 3 3 rather than 1 2 1 3
Upvotes: 4
Views: 9077
Reputation: 22740
I describe what you are doing here:
int[] a = new int[5];
int[] b = a;
Upvotes: 2
Reputation: 10843
The contents of the int array may not be references, but the int[] variables are. By setting b = a
you're copying the reference and the two arrays are pointing to the same chunk of memory.
Upvotes: 6
Reputation: 49197
Both a
and b
points to (is) the same array. Changing a value in either a
or b
will change the same value for the other.
Upvotes: 0
Reputation: 12056
you are not creating a new instance by int[] b = a
if you need new instance (and your expected result) add clone()
: int[] b = a.clone()
good luck
Upvotes: 0