• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Another Garbage Collection Question

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Would you turn that thing down? I'm controlling a mind here! Look ... look at the tiny ad ...
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic