Hello Prasanna,
I found this in JLS,
15.13.1 Runtime Evaluation of Array Access
An array access expression is evaluated using the following procedure:
First, the array reference expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason and the index expression is not evaluated.
Otherwise, the index expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason.
Otherwise, if the value of the array reference expression is null, then a NullPointerException is thrown.
Otherwise, the value of the array reference expression indeed refers to an array. If the value of the index expression is less than zero, or greater than or equal to the array's length, then an ArrayIndexOutOfBoundsException is thrown.
Otherwise, the result of the array access is the variable of type T, within the array, selected by the value of the index expression. (Note that this resulting variable, which is a component of the array, is never considered final, even if the array reference expression is a final variable.)
15.13.2 Examples: Array Access Evaluation Order
In an array access, the expression to the left of the brackets appears to be fully evaluated before any part of the expression within the brackets is evaluated. For example, in the (admittedly monstrous) expression a[(a=b)[3]], the expression a is fully evaluated before the expression (a=b)[3]; this means that the original value of a is fetched and remembered while the expression (a=b)[3] is evaluated. This array referenced by the original value of a is then subscripted by a value that is element 3 of another array (possibly the same array) that was referenced by b and is now also referenced by a.
Thus, the example:
class
Test {
public static void main(
String[] args) {
int[] a = { 11, 12, 13, 14 };
int[] b = { 0, 1, 2, 3 };
System.out.println(a[(a=b)[3]]);
}
}
prints:
14
because the monstrous expression's value is equivalent to a[b[3]] or a[3] or 14.