37

According to the JLS, runtime evaluation of an array access expression behaves as follows:

  1. 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.
  2. Otherwise, the index expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason.
  3. Otherwise, if the value of the array reference expression is null, then a NullPointerException is thrown.

So this code will print: java.lang.NullPointerException, index=2

class Test3 {
    public static void main(String[] args) {
        int index = 1;
        try {
            nada()[index = 2]++;
        } catch (Exception e) {
            System.out.println(e + ", index=" + index);
        }
    }

    static int[] nada() {
        return null;
    }
}

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?

senseiwu
  • 5,001
  • 5
  • 26
  • 47
Andrei Nepsha
  • 512
  • 3
  • 14
  • 1
    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 Ali Mar 14 '19 at 11:10
  • 9
    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. – Seelenvirtuose Mar 14 '19 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. – biziclop Mar 14 '19 at 11:35
  • 2
    … which in turn is a duplicate of [Is the array index or the assigned value evaluated first?](https://stackoverflow.com/questions/20339242/is-the-array-index-or-the-assigned-value-evaluated-first?lq=1) – fantaghirocco Mar 14 '19 at 13:22
  • @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 Nepsha Mar 14 '19 at 13:43

4 Answers4

38

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
14

This is because in the generated bytecode there are no explicit null checks.

nada()[index = 2]++;

is translated into the following byte code:

// evaluate the array reference expression
  INVOKESTATIC Test3.nada ()[I
// evaluate the index expression
  ICONST_2
  DUP
  ISTORE 1
// access the array
// if the array reference expression was null, the IALOAD operation will throw a null pointer exception
  DUP2
  IALOAD
  ICONST_1
  IADD
  IASTORE
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34
  • That’s swapping cause and effect. If the specification said the `null`-tests had to happen before the index evaluation, there were explicit `null` checks. – Holger Apr 04 '19 at 16:16
8

The basic byte code operations are (for an int[])

ALOAD array_address
ILOAD index
IALOAD array_element_retrieval

The IALOAD does the null pointer check. In reality the code is a bit more elaborate:

  1. calculate array address
  2. calculate index
  3. IALOAD

So the answer is: it would need an extra checking operation after the array address is loaded, in anticipation of the array access.

Behavior by straight implementation.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
8

The decision may be partially be rooted in performance.

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.

Michael
  • 41,989
  • 11
  • 82
  • 128