Reputation: 24748
public class Conversions {
public static void main(String[] args) {
int index = 3;
int[] arr = new int[] { 10, 20, 30, 40};
arr[index] = index = 2; //(1)
System.out.println("" + arr[3] + " " + arr[2]);
}
}
I have this and it gives:
2 30
I was hoping it will give
40 2
At (1) Why was the value of the index in assignment not changed to 2 ( and kept as 3). ?
Upvotes: 5
Views: 1012
Reputation: 15278
Java language Specification: 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.
Otherwise, the index 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 and the right-hand operand is not evaluated and no assignment occurs.
Otherwise, the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
[...] (further steps are explained)
As you can see the index is evaluated before the right-hand side of the assignment.
Upvotes: 5
Reputation: 16263
arr[index]
).Upvotes: 1
Reputation: 272447
The right-associativity of =
implied by section 15.26 of the Java Language Specification (JLS) means that your expression can be represented as a tree, thus:
=
+------+-------+
| |
arr[index] =
+----+----+
| |
index 2
But then, section 15.7 states:
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
Therefore, arr[index]
is evaluated before index = 2
is, i.e. before the value of index
is updated.
Obviously, you should never write code that relies on this fact, as it relies on rules that almost no reader understands.
Upvotes: 11