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 : )
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.
SCJP 6 || SCWCD 5
Your mind is under my control .... your will is now mine .... read this tiny ad