Why String is Immutable in Java?
Why String is Immutable in Java?
Collapse
X
-
Something related https://bytes.com/topic/java/answers...ng#post3826024
Consider two string objects with the same content, JVM would allocate the same memory space for em in the pool and enable what is called "object sharing". If you want to see the proof that it's happening behind the scenes, verify the hashcode of both objects. Now try changing the content of one of the objects and print the hashcode. It'd be different. Why immutable? Since they both are using the same memory area; imagine one object manipulating the content. The changes would be reflected in the other one too, which is something you wouldn't want. The garbage collector isn't usually allowed in this area because of the same reason. It wouldn't want to free the memory space just when one object is done using it. -
The string is Immutable in Java because String objects are cached in the String pool. ... Another reason why String class is immutable could die due to HashMap. Since Strings are very popular as the HashMap key, it's important for them to be immutable so that they can retrieve the value object which was stored in HashMap.Comment
-
-
The String is Immutable when String literals are shared among multiple customers; there is a risk where one customer's action would influence all other customers. A string is widely used as a parameter for various java classes. If String is not immutable, a file would be changed and lead to a serious security threat.Comment
-
In Java, the string is immutable because of security, synchronization and concurrency, caching and class loading. The String objects are cached in the String Pool and it makes String immutable.Comment
Comment