• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Another Garbage Collection Question

 
suneeta prabhu
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic