+ 6

int[]b=a : why does a change if i change b?

int[]a={1,3,4,5}; int[]b=a; b[2]=10; System.out.println(a[2]); the result is 10 ! can someone explain to me why a is touched? is b a reference to a?

16th Apr 2017, 11:43 PM
Johann Leis
Johann Leis - avatar
3 ответов
+ 16
Good question. :> Try doing: int a[] = {1,2,3,4}; System.out.println(a); You will realise that a is actually a memory address. When you are assigning a to b, you are assigning address of a to b and hence, if either values in a or b are altered, the changes will reflect on both sides. This act is called the shallow-copy of a to b. On the other hand, a deep-copy would be to assign the values of the array to another array by using a loop. for (int i = 0; i < array_size; i++) { b[i] = a[i]; } In this case, the memory address of both arrays are different and changes made to an array will not reflect on the other.
16th Apr 2017, 11:47 PM
Hatsy Rei
Hatsy Rei - avatar
0
I dont know if this right or not but this is how understand the code in my head. int[]a={1,3,4,5}; //declaring array 'a' int[]b=a; // changing array a to 'int[]b={1,3,4,5};' b[2]=10; // stating that the third number in array b is now 10 instead of 4. System.out.println(a[2]); // array a= array b. Thus the fourth number in the array is the same. thus, im thinking they (a and b) are 2 names for the same array. I might be wrong though, i just enjoyed trying to figure it out lol
16th Apr 2017, 11:52 PM
Mogammad Shameer Losper
Mogammad Shameer Losper - avatar
0
An array declaration is mainly a pointer to a memory address –it doesn't hold actual values.
17th Apr 2017, 8:26 AM
Álvaro