• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why not NullPointerException

 
pooja jain
greenhorn
Ranch Hand
Posts: 213
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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 .
 
Jay Pawar
Ranch Hand
Posts: 411
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The object a is a member of class B and not local reference of class A.
 
Jeff Bosch
Ranch Hand
Posts: 805
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
pooja jain
greenhorn
Ranch Hand
Posts: 213
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 71
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 411
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
should do it like this:

void m2() {
A a = new A();
}
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic