Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 229
IgorDiy Avatar asked Feb 25 '23 01:02

IgorDiy


2 Answers

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.

like image 155
stevevls Avatar answered Feb 27 '23 08:02

stevevls


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]
like image 21
evilone Avatar answered Feb 27 '23 08:02

evilone