Why was the String class designed in a way that instances of this class are pooled as well as immutable?
Thanks & Regards, Vidyakar Sharma.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With