This following question is from JavaCaps (http://www.javacaps.com/scjp_gar.html) and I was wondering if the answer they gave is correct. Here is the question: From the following code how many objects are garbage collected? String string1 = "Test"; String string2 = "Today"; string1 = null; string1 = string2; [a] 1 [b] 2 [c] 3 [d] 0 The answer they gave is [a] 1. Is this correct? I thought it would be zero. Wouldn't string1 not be eligible for garbage collection since it now is assigned string2? Thanks in advance!
Hi, In principle the answer is correct: String string1 = "Test"; String string2 = "Today"; string1 = null; string1 = string2; Objects are ellegible for garbage collection as soon as there is no reference to the object anymore, so in line 3, the reference to "Test" is set to null. in line 4 string1 refers to "Today", so there is no reference to the string object "Test" anymore, which would make it ellegible for garbage collection. However keep in mind that (but this is probably besides the point of this particular question): - you can not guarantee that objects are garbage collected, you can only state that an object is ellegible for garbage collection - string literals behave differently -> in fact string literals are created in a pool of string literals, and they are not ellegible for garbage collection. Greetings, TK
[ May 26, 2002: Message edited by: Thomas Kijftenbelt ]
Okay, so I came across another question: How many objects are eligible for garbage collection once execution has reached the line labeled Line A? String name; String newName = "Nick"; newName = "Jason"; name = "Frieda"; String newestName = name; name = null; //Line A The answer they give is 1. But I thought it would've been 2 (Nick and Frieda) following the results of the other question I posted... I am so confused.
As weird as this may sound, the correct answer is 0. String literals are never garbage collected. There is a special reference kept for each String literal from a "String constants table." You can find a good explanation of it in this thread. If you have any more questions, please ask. In addition, this thread displays a good strategy for solving these problems. Corey [ May 29, 2002: Message edited by: Corey McGlone ]