Why is the output in this example 1?
public static void main(String[] args){
int[] a = { 1, 2, 3, 4 };
int[] b = { 2, 3, 1, 0 };
System.out.println( a [ (a = b)[3] ] );
}
I thought it would be 2. i.e., the expression is evaluated as:
a[(a=b)[3]]
a[b[3]] //because a is now pointing to b
a[0]
Shouldn't a[0] be 2 because a is pointing to b?
Thanks in advance.
That weirded me out as well... however, check section 15.7.1 over here
Essentially, operands are evaluated from left to right. But also note this:
It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.