• 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

Is my thinking correct?

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String string1 = "Test";
String string2 = "Today";
string1 = null;
string1 = string2;
The object which string1 originally pointed to is eligible for garbage collection after these four lines?
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Santosh
The subject of stoing literals and garbage collection has been raised at least a few million times.
Here is one thread with some info for you.

You can also try to
search for the answers.
 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Santosh Bapat:
String string1 = "Test";
String string2 = "Today";
string1 = null;
string1 = string2;
The object which string1 originally pointed to is eligible for garbage collection after these four lines?


To my knowledge, "Test" will be eligible for garbage collection immediately after line 3. "Today" will be eligable for garbage collection only if both string1 and string2 are set to null or to other string objects.
HTH
Alex
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by alex earnshaw:

To my knowledge, "Test" will be eligible for garbage collection immediately after line 3. "Today" will be eligable for garbage collection only if both string1 and string2 are set to null or to other string objects.
HTH
Alex


I believe that since the code is using string literals, "Test" is never eligible for collection.
The string literal is placed into the pool and as such has something always referencing it.
Now if the code said:
String string1 = new String("Test");
String string2 = new String("Today");
string1 = null;
string1 = string2;
then, the first object is eligible when string1 is set to null.
Of course if I'm wrong someone will correct me
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic