This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi i have one doubt on this question.i thought the answeris c.2 objects are eligible for garbage collection.object 'nick' is also eligible for garbage collection.becaure newname refer to 'jason'.'Freida' is garbage collected because it is null. can anyone explain wheather my guess was correct or not. preparing for scjp1.4
Please Check this thread. "Nick" String Object is in the String Literal Pool.
Joined: May 05, 2006
Thanks to wise and Naseem, but still I am not clear about this question. Here is my explanation about this qn.
String newName = "Nick"; Nick is created in heap,with a newName referencing it.Also reference is stored in String Literal Pool table. So it has two reference, one is with newName and the other is in String Literal Pool.
newName = "Jason"; //same as new String("Jason");
Jason Object is created and its only reference is new Name. Point to note, Nick has still one reference from string literal pool.
name = "Frieda"; //same as new String("Frieda");
Frieda Object is created and its only reference is name.
String newestName = name;
newestName also refers to Frieda Object. Hence two references to Frieda Object (name and newestName)
name = null;
name is made null, but still there is a reference to Frieda Object through newestName. hence "Frieda" is not eligible for GC. "Jason" is referenced by newName. Hence it is not eligible for GC. "Nick" is in String Literal Pool. That is there is a reference to Nick from a constant pool.(according to corey tip line).
Your explanition sounds perfect. But here is how I feel thinds go:
The moment you do newName = "Jason"; then the String object "Nick" becomes like an orphan object having no variable referencing it. This object is simply LOST. Since now we do not have any refernce to "Nick", and so "Nick" object is eligible for garbage collection.
I am not sure whether Strings in String Literal Pool are garbage collected or not. I have to confirm on this. I belive they are GC. If not then think about a large probram where a lot of String objects are created. If GC was not possible then the String Literal Pool would have a huge collection of String objects, resulting in high consumption of memory , and the very first idea of having GC goes haywire.
So I believe that there will be 1 object eligible for GC. Please correct me if I am wrong anywhere in my explanation.
With Love, Bonny
"Life is like an ice-cream, Enjoy it before it melts..."