• 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

string literal GC

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Careful about String class instantiation in exam and garbage collection, the String s = "hello"; s = null; is not garbage collected but String s = new String ("hello"); s = null; is garbage collected.
Can somebody explain this? It is kinda conflicting...
 
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
>>String s = "hello";
>>s = null;
Java optimizes handling of string literals by implementing them as anonymous objects that can be shared.
Strings that have the same literal contents share the same anonymous object.
Consider this code:

Both of the print statement will print true.
This means that this form of initialization does not create new objects. It only creates a reference that points to an anonymous object that cannot be garbage collected.

>>String s = new String ("hello");
>>s = null;
This form of initialization, however, creates a new String object.
Again, consider this code:

The first print statement will print false.
s2 now points to a newly created object that can be garbage collected.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic