The question is: for what reason do we need to first evaluate the index = 2 expression and not just throw the NullPointerException once the array reference is evaluated to null? Or in other words - why is the order 1,2,3 and not 1,3,2?

Firstly you have to initialize an array and secondly the priority of equals sign is high that's why its given null pointer exception.
– Ammar AliMar 14 at 11:10

8

Asking on SO why the JLS is written the way it is will not give you any good answer unless it maybe comes from one of the designers of the Java language.
– SeelenvirtuoseMar 14 at 11:17

4

They had to choose something, and both options can produce "unexpected" scenarios. (I.e. scenarios that behave in a not very intuitive way). The option that was chosen seems to be more in line with how expression evaluation works in other parts of Java.
– biziclopMar 14 at 11:35

@fantaghirocco i didn't ask about how java evaluates an array index expression, it's described in the question. I just wanted to know what the reason behind that's behavior.
– Andrei NepshaMar 14 at 13:43

In order to know that index = 2 is not going to be required, we would have to first evaluate nada() and then check whether it was null. We would then branch on the result of this condition, and decide whether or not to evaluate the array index expression.

Every perfectly valid array index expression would be made slower by one additional operation, just for the sake of saving code - code that is going to throw an exception anyway - from evaluating one expression unnecessarily.

It is an optimistic approach which works better in the majority of cases.