1. String myString = new String("Batman"); 2. String mySecond = new String("Robin"); 3. System.out.println(myString + mySecond); 4. myString = null; 5. myString = mySecond; 6. mySecond = null; at which line is the first string (myString) eligible for GC? To my understanding, it's in line 4 that myString eligible for GC. But how to deal with line 5, if myString is garbage collected instantly in line 4( I know gc() is not guranteed to run in line 4, but there is the possibility, right?) What is the right answer? Thanks! [This message has been edited by maha anna (edited July 22, 2000).]
Hi Linda, Remember that the String object created by new String("Batman") is distinct from the String reference myString. When the assignment <CODE>String myString = new String ("Batman");</CODE> is executed, the String reference myString refers to the String object created. When the String reference myString is set to null, it no longer refers to any object but it still exists just like any other variable. Also, the String object that myString referred to now has no object references referring to it anymore. Hence, there is no way for any instruction to access this object. Java therefore decides that this object can be removed without causing any problems. This is garbage collection.
May the Moose be with you.
Joined: Mar 14, 2000
Hi Rolf, If myString 'object' is garbage colected after Line 4 Then how is it possible to assign a to myString again in line 5. can u elaborate what u exactly mean by 'object removed'. Am i missing any point here.
Originally posted by eram: Hi Rolf, If myString 'object' is garbage colected after Line 4 Then how is it possible to assign a to myString again in line 5. can u elaborate what u exactly mean by 'object removed'. Am i missing any point here.
Actually myString is not an object but contains a reference that points to the object.Setting myString to null will cause the object to lose ite reference which eventually will lead to its garbagecollection.'myString' is like a variable which can be assigned different values thus assigning it to null does not make it non reusable