Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this javacode exactly do?

Tags:

java

arrays

I have an Array a1 and a2

What does the code a1=a2; exactly do? Copy all elements in Array a1? That´s what I thought but that does not seem to happen?

No it copies no array elements whatsoever but rather assigns a references. In sum it means that a1 refers to the exact same array object reference as a2 does.

Code:

int[] a1 = new int[] { 1, 2, 3 };
int[] a2 = new int[] { 4, 5, 6 };
a1 = a2;
a1[1] = 3;
a2[2] = 2;
a2 = a1;
for (int i = 0; i < a2.length; i++) {
System.out.print(a2[i] + " ");
}

Can someone explan why the outcome is 4 3 2 and not 4 3 6?

like image 577
user3084311 Avatar asked Aug 13 '26 10:08

user3084311


2 Answers

No it copies no array elements whatsoever but rather assigns a references. In sum it means that a1 refers to the exact same array object reference as a2 does.

If you want to copy elements, you could use a for loop, or System.arraycopy(...)

If you want to do a deep copy, then I would use a for loop, and make copies of each of the elements, perhaps with a copy constructor or by cloning, or whatever makes the most sense for the items held by the array.


Edit

Your additional code with my comments:

int[] a1 = new int[] { 1, 2, 3 }; 
int[] a2 = new int[] { 4, 5, 6 }; 
a1 = a2;  // both array variables refer to the one same array object, 4, 5, 6
a1[1] = 3;   // you're changing the one single array's 2nd item
a2[2] = 2;   // you're changing the same array's 3rd item
a2 = a1;  // this does nothing really as they already refer to the same object
for (int i = 0; i < a2.length; i++) { 
  System.out.print(a2[i] + " "); 
}

So thats why the result is 4 3 2 and not 4 3 6?

Yep, see comments

like image 73
Hovercraft Full Of Eels Avatar answered Aug 16 '26 01:08

Hovercraft Full Of Eels


It makes a2 refer to the same array that a1 does.

Only one copy of the array actually exists in memory. This means that if you start changing elements of a1, those changes will show up when you read from a2.

like image 23
user1445967 Avatar answered Aug 16 '26 01:08

user1445967