File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String" Watch "String" New topic


shruti patel
Ranch Hand

Joined: Mar 10, 2008
Posts: 52

even though String is immutable which creates hell of the objects,still we use it repeatedly in our application.why?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

For numerous reasons.

Some of those:
- it's about the only thing that can be printed to the console or most user interface controls. Even primitive types such as int are converted to Strings
- because they are immutable they are perfect as keys for Maps
- it just makes sense to store (fixed) alphanumeric information in Strings

Now about the creation of objects. Sure, a lot of methods of the String class return a new String object. But a lot of the time, the original becomes available for garbage collection right afterwards. In the end, the number of String objects doesn't change that much over time in most applications.

Now there is a trick to reduce the number of String objects somewhat. When you know that you need to do a lot of String concatenation, removal or replacing, you should consider using StringBuilder. Unlike String, this is mutable, and if you are finished you can create a String using the toString method.

How To Ask Questions How To Answer Questions
vaibhav mishra
Ranch Hand

Joined: Jun 18, 2008
Posts: 168
according to K&B

one of the key goals of any good programming language is to make efficient use of memory.As applications grow,it is very common for String literals occupy large amounts of a program's memory,there is often a lot of redundancy within the universe of String literals for a program. To make Java more memory efficient,the JVM sets aside a special area of memory called the String constant pool.When the compiler encounters a String literal, it checks the pool to sec if an identical String already exists.If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created.(The existing String simply has an additional reference.) Now we can start to see why making String objects immutable is such a good idea.If several reference variables refer to the same String without even knowing it,it would be very bad if any of them could change the String's value.
[edit]Corrected tags. CR[/edit]
[ July 17, 2008: Message edited by: Campbell Ritchie ]

I agree. Here's the link:
subject: String
It's not a secret anymore!