Originally posted by majohnad majohnad:
Hi,
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
In the above code in which line s is available for garbage collection.
Thnaks in Advance
Unless I'm mistaken, I'd say line 3.
s initially contains a reference to the String object created by String s = new String("abc").
I always draw a diagram like this:
r ------------> (1)
s ------------> (2)
incrementing the number on the right (the heap) every time a new object is created and showing which reference variables point to which objects, then it is easy to see when an object is eligible for GC when it has no refs pointing to it. So in this case after line 3 we have:
(1)
(2)
(3)
r ------------> null
s ------------> (4)
So we can see that 3 objects are eligible for GC. (3) is the object created at line 1 and (4) is the new String object resulting from the addition at line 3.
Also, I presume your question should read:
"in which line is the object initially assigned to s eligible for GC". s itself is never eligible for GC as it is a stack variable and therefore not on the garbage collectible heap.
(I assume I am right in thinking that when you add Strings the new String does not contain references to the Strings that were added but merely constructs a new String object out of the data contained in the two added Strings.)