aspose file tools*
The moose likes Java in General and the fly likes Does string immutability not come at cost of taking more memory? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Does string immutability not come at cost of taking more memory?" Watch "Does string immutability not come at cost of taking more memory?" New topic
Author

Does string immutability not come at cost of taking more memory?

Monica. Shiralkar
Ranch Hand

Joined: Jul 07, 2012
Posts: 644
Strings are immutable but does it not add to it taking more memory.(Despite the concept of string pooling).
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61433
    
  67

How did you come to that conclusion?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Monica. Shiralkar
Ranch Hand

Joined: Jul 07, 2012
Posts: 644
Since strings are unchangeable everytime new String has to be created(Unless it is in the pool).Thus despite the pooling concept one ends up creating new objects each time and thus taking memory.

thanks
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61433
    
  67

Ignoring the string pool, any unused string are garbage collected.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14270
    
  21

There are certain things you should not do with strings, because they are immutable. For example, repeatedly adding to a string in a loop is bad:

When you do this, in each iteration of the loop, a new String object is created into which the content of the previous String object is copied, with the extra "yip" appended.

Instead of doing this, you should use StringBuilder, which is essentially a mutable String object:

So, there are certainly situations where you have to be aware what happens with your strings, and you'd better use a StringBuilder instead.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Monica. Shiralkar
Ranch Hand

Joined: Jul 07, 2012
Posts: 644
thanks
 
jQuery in Action, 2nd edition
 
subject: Does string immutability not come at cost of taking more memory?