Reputation: 67
Why was the String
class designed in a way that instances of this class are pooled as well as immutable?
Thanks & Regards, Vidyakar Sharma.
Upvotes: 2
Views: 208
Reputation: 31
for mutable strings check out: StringBuffer and StringBuilder from java.lang.
Upvotes: 1
Reputation: 692121
If String weren't immutable you wouldn't be able
In short, life would be much more complicated, because you would have to make defensive copies of the String everywhere, and StackOverflow would be flooded with questions regarding subtle bugs where some String is stored in a map but can't be found anymore.
Upvotes: 3
Reputation: 11726
An Immutable object is one of the best design decisions that exists. It's intended to simplify concurrent programming. Threads sharing the object can not interfere with each other.
If you want mutable strings check out: StringBuffer and StringBuilder
Upvotes: 2
Reputation: 1503180
String objects aren't usually pooled - only string constants are pooled automatically via interning. (You can call intern
manually of course, or even create your own pools via HashSet<String>
etc.) This is only safe because strings are immutable - and it makes sense to make sure that any compile-time constant only occurs once in memory.
You wouldn't want to pay the price of looking up the string in the intern pool (or keeping it around forever) for every string in the system, because there may be many different strings over time. However, the string constants loaded from classes will stick around as long as those classes do, and by interning them once you can reduce the memory required as GC churn.
Upvotes: 6
Reputation: 199324
Pooled to avoid having duplicate objects that represent the same.
Immutable to make it easier to share it.
Upvotes: 0