Why is a Java array index expression evaluated before checking if the array reference expression is null?

An array access expression has two sub-expressions:

An array access expression contains two subexpressions, the array reference expression (before the left bracket) and the index expression (within the brackets).

The two sub-expressions are evaluated before the array access expression itself, in order to evaluate the expression.

After evaluating the two sub-expressions

nada()[index = 2]++;

becomes

null[2]++;

Only now the expression is evaluated and the NullPointerException is thrown.

This is consistent with the evaluation of most expressions in Java (the only counter examples I can think of are short circuiting operators such as && and ||).

For example, if you make the following method call:

firstMethod().secondMethod(i = 2);

First you evaluate firstMethod() and i = 2, and only later you throw NullPointerException if firstMethod() evaluated to null.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)