File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes garbage collection query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "garbage collection query" Watch "garbage collection query" New topic

garbage collection query

Sneha Kapoor
Ranch Hand

Joined: Jun 08, 2009
Posts: 49

At the point that line 12 is reached, how many objects are eligible for garbage collection?

I thought that 2 objects are eligble but answer is 1

Source : Apress SCJP Book
Yogesh Bali

Joined: May 29, 2009
Posts: 22

yes its correct the answer is one .... the object created by r1 only is eligible for gc..
3 objects created by r1, r2 and r3.. let for our convenience say the object created by r1 is A, object created by r2 is B and object created by r3 is C..
till line 7, what we have is

object A having only one reference -- r1
object B having 3 references -- r2, r4, and r5
object C having only one reference -- r3.

now by line 8, r2=null, means for object B now we are having 2 references only -- r4 & r5. Also our r2 now contains null, not refering to anything else.

by line 9, r4=r2 implies r4 also containing null, so our object B now having only one reference r5.

by line 10, r1=r5 implies our r1 which is refering to object A is now refering to object B.. because r5 points to object B.

and r1 was the only reference to object A, so no one is pointing to object A by now...
object B is referred by r1 and r5...
object C is referred by r3...

So only 1 object eligible for gc..

Java is Easy.. Enjoy studying it
Have a good time : )
Michael Angstadt
Ranch Hand

Joined: Jun 17, 2009
Posts: 277

Try this. Draw an empty square whenever a new instance of an object is created. Put the names of the references that point to that object inside the square. Cross out a reference if it is set to null or assigned to a different object. Any boxes that are empty at the end are eligible for garbage collection:

One box (the left box) is empty, so one object can be garbage collected.

I agree. Here's the link:
subject: garbage collection query
It's not a secret anymore!