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
null[2]
Moderator: admin
-
- Posts: 2
- Joined: Sun Aug 23, 2020 1:27 pm
- Contact:
-
- Site Admin
- Posts: 10055
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: null[2]
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.
Who is online
Users browsing this forum: mcpunjabi and 39 guests