In the first code snippet the interesting part is
int val = (a = b)[3]
Here there are two assignments. The first one (a = b
) will happen first and lets the variable a
also reference the array that b
refers to (note that the old array is not referenced anymore and thus is eligible to being garbage collected).
Afterwards you ask for the element on index 3. And that is the value "0". The output then asks for the element on index 0 in that array. And as you can see, this is the value "2". Remember that a
now refers to the same array as b
.
In the second code snippet you are doing all in the same line:
System.out.println(a[val = ((a = b)[3])]);
Although the assignments and indexing look the same, the major difference here is that you are accessing the array (referenced by a
) before you reassign the variable.
So after all assignments are done, the variable val
has the same value "0" and the variable a
refers to the same array as b
. But now the first element (index 0) in the old array will be looked up. And that is "1".