• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Is my thinking correct?  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
  • 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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!