wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Another Garbage Collection Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Another Garbage Collection Question" Watch "Another Garbage Collection Question" New topic
Author

Another Garbage Collection Question

suneeta prabhu
Greenhorn

Joined: Jun 03, 2001
Posts: 8
hi all,
this is taken from javaprepare mock exam. pls explain what is the answer and why-
At what stage in the following method does the object initially referenced by s becomes available for garbage collection. Select the one correct answer.
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

r and s are references to 2 different string objects b'cos they are created using "new". am i right?
suneeta prabhu
Greenhorn

Joined: Jun 03, 2001
Posts: 8
I changed the code as follows-
class X{
void X() {
String r = new String("abc");
String s = new String("abc");
r = r+1; //1
r = null; //2
s = s + r; //3
System.out.println(s);
}
public static void main(String args[]) {
X x = new X();
x.X();
}
}
when run this code prints "abcnull". The address of this new string has been assigned to the reference variable s. So the object initially referenced by s no longer has any references pointing to it. Hence it is eligible for garbage collection. Am i right or am i missing something? Could someone throw light on this please?
suneeta
kevin goon
Ranch Hand

Joined: Jun 12, 2001
Posts: 62
i think the answer to that is right after the line 3 has been executed. s initially points to "abc". but after the assignment, s points to the newly retruned concatenated String Object
Jyotsna Umesh
Ranch Hand

Joined: May 09, 2001
Posts: 94
Hi,
I think kevin you are right, after line 3 string s refers to new conctenated string, so earlier reference is lost and it is eligible for garbage collection.
Jyotsna
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Another Garbage Collection Question
 
Similar Threads
Garbage collection
A question about Garbage Collection!
Garbage Collection
Garbage Collection
GC doubt