Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Objects - GC

 
Lovleen Gupta
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question is - how many objects are eligible for garbage collection at //doStuff?



My understanding says that there should be 4 objects (c1, c1.story, c2, c2.story). But the answer is 2. Please explain why is it so?

Thanks.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hi Guptajee,
You should always see at how many times "new" is being used at first hand.
Inside the main method you created 2 objects; dont forget Short story =5; in the class definition, it is for every object, Short is wrapper not primitive. Inside the go method there wont be affect of making bs =null to the original main reference. It would have local impact at you know copy of the reference is passed to the method so if any internal modification is made to the object as "changing Person's name or age" using passed reference, it would affect the calling method but setting the reference to null in the called method wont affect the calling method object reference; so dont worry about that.

When you set the c1= null; Two objects become eleigible for garbage collection; the first the object referenced by c1 and the object referenced by the story referecen that is encapsulated in the object. So two objects would be eligible for garbage collection.


Hope this helps,

Thanks and Regards,
cmbhatt
 
Rajeswari Kumar
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lovleen
This issue is already discussed. Please check the link
http://www.coderanch.com/t/262041/java-programmer-SCJP/certification/Garbage-Collection-any-one-explain

regards
Rajeswari
 
Lovleen Gupta
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Chandra & Rajeswari..
It is clear now..!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic