File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Monica Shiralkar
Ranch Hand
Posts: 825
1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64194
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How did you come to that conclusion?
 
Monica Shiralkar
Ranch Hand
Posts: 825
1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64194
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ignoring the string pool, any unused string are garbage collected.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Monica Shiralkar
Ranch Hand
Posts: 825
1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic