null[2]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
dantan267@gmail.com
Posts: 2
Joined: Sun Aug 23, 2020 1:27 pm
Contact:

null[2]

Post 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

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: null[2]

Post 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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 29 guests