| Author |
why not NullPointerException
|
pooja jain
greenhorn
Ranch Hand
Joined: Jan 12, 2005
Posts: 213
|
|
My doubt is , why it is not throwing null pointer exception . the object we have asigned to a reference got create in a method ( m2 ) so after terminating this method , that object should also get end ( eligible for GC ) and a reference should again point to null & then NullPointerException . please help . Thanks .
|
:d
|
 |
Jay Pawar
Ranch Hand
Joined: Aug 27, 2004
Posts: 411
|
|
|
The object a is a member of class B and not local reference of class A.
|
Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.
|
 |
Jeff Bosch
Ranch Hand
Joined: Jul 30, 2003
Posts: 804
|
|
|
If you want to get rid of the object referenced by a, then you need to set a = null. Now the object is freed for garbage collection. Had you declared a in addition to defining it within method m3, then it would have local scope and would die at the end of the method execution.
|
Give a man a fish, he'll eat for one day. <br />Teach a man to fish, he'll drink all your beer.<br /> <br />Cheers,<br /> <br />Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
|
 |
pooja jain
greenhorn
Ranch Hand
Joined: Jan 12, 2005
Posts: 213
|
|
Originally posted by Jay Pawar: The object a is a member of class B and not local reference of class A.
a is not object . a is pointing to an object & that object I am creating in a method scope . so after method , how it can be live ?
|
 |
Jeff Jetton
Ranch Hand
Joined: Mar 29, 2005
Posts: 71
|
|
Originally posted by pooja jain: a is not object . a is pointing to an object & that object I am creating in a method scope . so after method , how it can be live ?
Yes, technically, a is not the object. But it is a reference to an object. That reference is declared outside the method. So even though you've created an object inside the method, you've assigned it to a reference that was created outside the method. As long as that reference is in scope, the object to which it points will not be eligible for garbage collection. - Jeff
|
 |
Jay Pawar
Ranch Hand
Joined: Aug 27, 2004
Posts: 411
|
|
Oops my mistake you are right a is not object it is reference.Need to get my mind out of C++ world. and the answer to your question is well explained by Jeff.
|
 |
Mike Zhong
Greenhorn
Joined: Mar 04, 2005
Posts: 4
|
|
should do it like this: void m2() { A a = new A(); }
|
 |
 |
|
|
subject: why not NullPointerException
|
|
|