Page 1 of 1

null[2]

Posted: Wed Apr 14, 2021 1:25 pm
by dantan267@gmail.com
Hi all,

I refer to Question 30 of the 808 Mock exam.

The following is the explanation from there:
If the array reference expression produces null instead of a reference to an array, then a NullPointerException is thrown at runtime, but only after all parts of the array reference expression have been evaluated and only if these evaluations completed normally.

This means, first index = 2 will be executed, which assigns 2 to index. After that null[2] is executed, which throws a NullPointerException. But this exception is caught by the catch block, which prints nothing. So it seems like NullPointerException is not thrown but it actually is.

In other words, the embedded assignment of 2 to index occurs before the check for array reference produced by getArray().

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. Note that if evaluation of the expression to the left of the brackets completes abruptly, no part of the expression within the brackets will appear to have been evaluated.

My Question: What is being meant by null[2]?

Regards,
Daniel

Re: null[2]

Posted: Wed Apr 14, 2021 11:48 pm
by admin
The explanation is trying the show how the expression will be evaluated and shows the result of each step. null[2] just means that the third element is being accessed on an array reference that is null. Accessing a null reference causes NPE.