permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt on garbage collection 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 "doubt on garbage collection" Watch "doubt on garbage collection" New topic

doubt on garbage collection

Charu Murali
Ranch Hand

Joined: Jul 12, 2002
Posts: 37
I came acroos the following qn in a mock exam.
At what stage in the following method does the object initially referenced by s becomes available for garbage collection. Select the one correct answer.

void method X() {
String r = new String("abc");
String s = new String("abc");
r = r+1; //1
r = null; //2
s = s + r; //3
} //4

1.Before statement labeled 1
2.Before statement labeled 2
3.Before statement labeled 3
4.Before statement labeled 4
the ans they have given is 4. But I think garbage collection can not be forced or determined. Can anyone please clarify me.
sean cee
Ranch Hand

Joined: Oct 24, 2000
Posts: 115
True, GC cannot be forced or determined.
But the wording of the question is
"when does it become ELIGIBLE for GC ?"
That means
"IF GC start to kick in, will it be a candidate for GC or not?"
and an object becomes candidate for GC only if there is no reference to it..
so the answer given is correct.

Sean <br />SCJP2, SCJP2p1.4, SCWCD
swarna kumar

Joined: Nov 11, 2001
Posts: 17
hi sean,
we can not force the GC, but if we can set the obj.ref variable to null, hinting the GC to garbage collect the objects referred by the variables.
so from this programm,how can we say the ans is 4,
could u pls correct me,
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
The question does not ask when the object initially referenced by s will be garbage collection, it asks, only, when will it be eligible for garbage collection. This is roughly synonymous to asking at what point are there no references to the object from an active part of the application. Let me rephrase the question like this to see if it makes more sense: "At what point, if the garbage collection process were to execute, would the object originally referenced by s be garbage collected?"
Therefore, 4 is the correct answer because, after the last line of code in that block is executed, there are no references to the object in question. There is no guarantee when, or even if, the object will be garbage collected. It is, however, eligible for garbage collection, which is what the question asks.
I hope that helps,

SCJP Tipline, etc.
I agree. Here's the link:
subject: doubt on garbage collection
It's not a secret anymore!