Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why String class was designed this way?

Tags:

java

jvm

jls

Why was the String class designed in a way that instances of this class are pooled as well as immutable?

Thanks & Regards, Vidyakar Sharma.

like image 503
Vidyakar Sharma Avatar asked Apr 26 '26 10:04

Vidyakar Sharma


2 Answers

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.

like image 54
Jon Skeet Avatar answered Apr 29 '26 00:04

Jon Skeet


If String weren't immutable you wouldn't be able

  • to safely return a String field from a getter without breaking encapsulation, because the caller might modify the contents of the string behind your back
  • to share a String between threads, because some thread might modify its content. All the accesses to the String would have to be synchronized.
  • to use Strings as keys in HashMaps/TreeMaps, because someone might change its value and thus its hashCode/comparison order
  • to pool Strings in order to have a single instance of the same constant string
  • to have a substring sharing the same char array of its string

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.

like image 32
JB Nizet Avatar answered Apr 29 '26 02:04

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!