posted 24 years ago
If you guys are worried about garbage collection of String literals for the exam, I wouldn't worry. I really doubt they would ask you about garbage collection and String literals. Much more likely they will ask you about garbage collection of objects created with the new operator (which are eligible for garbage collection when there are no longer any valid references to them).
But if you still want to know, this explanation was posted earlier and it seems very clear:
Jim Yingst
sheriff
posted February 24, 2000 02:02 PM
OK, this shouldn't come up on the exam, but I don't want this misinformation to continue to spread, so if you want to know about which kinds of strings are never collected, read on:
Sree- that's a myth I have been trying to stamp out lately. Forget about whether the new operator was used -
that isn't what determines whether a string can be collected. There are many ways to create new strings without a visible "new" operator, and almost all of them create an ordinary String which can be collected. The only exceptions are:
1.Strings which appear as literals in the code without any other operations being done to them, e.g.: String a = "literal";
2.Strings which are the result of a constant-valued expression, e.g. String b = "not a " + "literal" + " but a constant";
or
String c = "Pi equals " + Math.PI;
(because Math.PI is final, it's considered constant)
3.Strings returned by the intern method, e.g.
String d = anotherString.intern();
Cases 1 and 3 should be easy to identiry; case 2 is a little harder - you have to look at each part of an expression to determine if it's a constant, i.e. if it's a variable, it needs to be final.
All the above examples are put in the intern pool, and can never be collected. All other kinds of strings are "normal" and can be collected (if there are no more references). So in this example:
String s = "good"
s+= "morning";
s = null;
"good" is a literal and can never be collected, but "goodmorning" can be collected (s += "morning" is equivalent to
s = s + "morning", and since s isn't a constant, the expression
s + "morning" isn't a constant expression).
[This message has been edited by Jim Yingst (edited February 24, 2000).]
Hope this helps.
Stephanie