posted 7 years ago
I'll admit that this one took me a bit to figure out as well. I did look at the other thread mentioned but the statement in the last post 'The method "setInt" does not even get executed' is incorrect. Here is the way I determined the answer:
On line 2, a new instance of Holder is created and assigned to the reference variable 'b'. Note that at this point, the value of b.link is null since nothing has been assigned to it yet
On line 4, the setIt method is invoked. Inside this method, the following statement is executed:
This is where the value of a.link (referred to in this method as x.link) is set to null. It is because b.link (or y.link in this method) is null at this point. Although b refers to a valid object, the b.link property has not been assigned anything at this point
The return value of the setIt() method is the a reference to the holder object 'x' (which is pointing the same object as the reference variable 'a') which is then assigned to b.link (so now b.link has a value but a.link still does not)
On line 5, the statement tries to invoke a method on a null object (b.link) and throws a NullPointerException