• 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

Garbage collection easy question

 
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could someone explain why the member "a" is not eligible for garbage collection after line 8.
1. public void method() {
2. String a,b;
3. a = new String("hello world");
4. b = new String("good bye");
5. System.out.println(a+b + "!");
6. a = null;
7. a = b;
8. System.out.println(a);
9. }
In the absence of optimization, after which earliest line the object a is definitly elibible to be garbage collected?
I anwered line 8.
The answer is line 6.
Please explain.

}
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi charlie,
It looks like the question should have been more like : which object initially refered by reference a ,is eligible for garbage collection ,and the answer would be 6
 
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In line 3, String a is created. a is the only reference to the object. In line 6 a is changed to null, meaning that nothing is referencing the original object, so the object is eligible to be garbage collected.
 
Charlie Swanson
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks
reply
    Bookmark Topic Watch Topic
  • New Topic