Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning an array reference to another array in Java

Tags:

java

arrays

int a[]={1, 2, 3, 4, 5};
int b[]={4, 3, 2, 1, 0};

a=b;

System.out.println("a[0] = "+a[0]);

This displays a[0] = 4 as obvious because a is assigned a reference to b.


If it is modified as follows

int a[]={1, 2, 3, 4, 5};
int b[]={4, 3, 2, 1, 0};        

System.out.println("a[(a=b)[0]] = "+a[(a=b)[0]]);  //<-------

then, it displays a[(a=b)[0]] = 5.


Why doesn't this expression - a[(a=b)[0]] yield 4, the 0th element of b even though it appears to be the same as the previous case?

like image 544
Tiny Avatar asked Dec 21 '25 09:12

Tiny


1 Answers

The second expression features an assignment expression inside an array indexer expression. The expression evaluates as follows:

  • The target of the indexer expression is selected. That's the original array a
  • The index expression is evaluated by first assigning b to a, and then taking the element of b at index zero
  • The index of the outer indexer is evaluated as b[0]
  • The index is applied to a, returning 5
  • The assignment of b to a takes effect. Subsequent accesses to a[i] will reference b, not the original a.

Essentially, your single-line expression is equivalent to this two-line snippet:

System.out.println("a[(a=b)[0]] = "+a[b[0]]); // Array reference completes first
a=b;                                       // Array assignment is completed last
like image 195
Sergey Kalinichenko Avatar answered Dec 23 '25 00:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!