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?
The second expression features an assignment expression inside an array indexer expression. The expression evaluates as follows:
ab to a, and then taking the element of b at index zerob[0]a, returning 5b 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With