This question was taken from Kathy Sierra SCJP 1.6. How many objects are eligible for garbage collections?
According to Kathy Sierra’s answer, it is C. That means two objects are eligible for garbage collection. I have given the explanation of the answer. But why is c3 not eligible for garbage collection (GC)?
class CardBoard {
Short story = 200;
CardBoard go(CardBoard cb) {
cb = null;
return cb;
}
public static void main(String[] args) {
CardBoard c1 = new CardBoard();
CardBoard c2 = new CardBoard();
CardBoard c3 = c1.go(c2);
c1 = null;
// Do stuff
} }
When // Do stuff is reached, how many objects are eligible for GC?
- A: 0
- B: 1
- C: 2
- D: Compilation fails
- E: It is not possible to know
- F: An exception is thrown at runtime
Answer:
- C is correct. Only one CardBoard object (c1) is eligible, but it has an associated
Shortwrapper object that is also eligible. - A, B, D, E, and F are incorrect based on the above. (Objective 7.4)
No object ever existed that
c3points to. The constructor was only called twice, two objects, one each pointed to byc1andc2.c3is just a reference, that has never been assigned anything but the null pointer.The reference
c3, that currently points to null, won’t go out of scope and be removed from the stack until the closing brace at the end of the main method is crossed.The object originally assigned to
c1is unreachable because thec1reference was set to null, but thec2reference has not been changed, so the object assigned to it is still reachable from this scope via thec2reference.