Consider
int b = 2; int[] a = new int[4]; a[a[b]] = a[b] = b = 2; for (int i = 0; i <= 3; i++) { System.out.println(a[i]); } The output is
2 0 2 0 I was expecting a[0] to be zero.
Consider
int b = 2; int[] a = new int[4]; a[a[b]] = a[b] = b = 2; for (int i = 0; i <= 3; i++) { System.out.println(a[i]); } The output is
2 0 2 0 I was expecting a[0] to be zero.
Excerpt from JLS 15.26.1. Simple Assignment Operator =
If the left-hand operand is an array access expression (§15.13), possibly enclosed in one or more pairs of parentheses, then:
First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
This means that a[a[b]] evaluates to a[0] as it's evaluated first. Then we proceed simply as a[0] = a[b] = b = 2, with the assignment taking place from right to left.
See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.1
I guess this thread might help you to understand the evaluation order in java: What are the rules for evaluation order in Java?
The most important part of this problem is that the first = is the actual assignment. In java the index is always evaluated befor the asignment, therefor a[a[b]] is the fist one in the evaluation order. And at this point a[b] is 0.
I think you are reading
a[a[b]] = a[b]=b=2;
from right to left and expecting the array and b to be reevaluated at each step, when in fact it seems like a and b are frozen at the time of the assignment. Consider the equivalent code:
1) int b = 2; //array initialized to 0 2) int[] a= new int[4]; // 0 0 0 0 // at this point a[b] is a[2] = 0, therefore below a[a[b]]=2 is equivalent to a[0]=2 3) a[a[b]] = 2 // 2 0 0 0 // the same: a[b] = 2 is equivalent to a[2] = 2 -note that the arrays are zero based 4) a[b]= 2 // 2 0 2 0 5) b=2;