• 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 of Strings

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I have read about String objects being cached. java maintaining a copy of Strig objects even if there are no refences pointing to them - which may be a cause of concern in large projects.
And that StringBuffer should be used instead of String class.
Can somebody help me with this - are only Strings created with assignment not garbage collected or all - ie created with new as well. Is there anything in the JLS on this ??
please help,
 
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Shailesh Misra:
I have read about String objects being cached. java maintaining a copy of Strig objects even if there are no refences pointing to them - which may be a cause of concern in large projects.

String literals in your application are not subject to garbage collection, but that's hardly a cause for concern. To the contrary - there is only one copy of any given string, no matter how often it is used in your application, which is a great space-saver. Strings created using the new operator are subject to garbage collection like anything else.

And that StringBuffer should be used instead of String class.

Only when you are modifying the String many times, e.g. appending to it. Strings are immutable, which means that all modifications of a String involve the creation of a new String, which often has to copy the char array that backs the String. If you perform concatenation using the + operator, a temporary StringBuffer is created. Do this a lot and the garbage collector will be flooded by little objects.
- Peter

[This message has been edited by Peter den Haan (edited October 25, 2001).]
reply
    Bookmark Topic Watch Topic
  • New Topic