Answer b (2 objects). seems to be the right answer.
Line 10 nulls c2 created on line 9 ( that's 1 object ) Line 11 nulls c1 created on line 8 ( that's 2 objects ) Line 10 assigns null to c3 which was never instantiated, so.. ( that's still 2 objects, right? )
Here two objects are eligible for garbage collection. But which are those two? At line no 10, no abject is created and null is assign to c3. At line no 11, one object is eligible for gargbage collection (The one which was created at line 8). Since CardBoard has one instance variable Short story, which is not reachable, this object also is eligible for garbage collection. Thus CardBoard and one Short object are eligible for garbage collection.
Hey, Here After line 10 ,the CardBoard objects at line 9 becomes eligible for Garbage Collection since c2 is made to point to null while calling in method go(). At line 11 ,the CardBoard object present in line 8 becomes eligible. Hence two cardboard objects becomes eligible for Garbage Collection.
I dont understand why Short object story becomes elligble for Garbage collection.
You can always modify the code to get an idea what is happening. But realize that System.gc may not always do what you want it to.
Joined: Aug 13, 2006
I'm not satisfied. This is the same example, sited in the K & B, SCJP 5 book (Page 266). It says.. Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.