IgorDiy
IgorDiy

Reputation: 939

Java array of primitive data types

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

Answers (4)

evilone
evilone

Reputation: 22740

I describe what you are doing here:

  1. creating an array of integers int[] a = new int[5];
  2. creating a reference to created array int[] b = a;
  3. adding integer to array "a", position 0
  4. overwriting previously added integer, because b[0] is pointing to the same location as a[0]
  5. adding integer to array "a", position 1
  6. overwriting previously added integer again, because b[1] is pointing to the same location as a[1]

Upvotes: 2

stevevls
stevevls

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

Johan Sjöberg
Johan Sjöberg

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

bestsss
bestsss

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

Related Questions