0 votes
in JAVA by
How string is immutable in java?

1 Answer

0 votes
by

Why string is immutable in java?

The string is Immutable in Java because 

1) String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client’s action would affect all another client. 

2) For example, if one client changes the value of String “ABC” to “abc”, all other clients will also see that value as explained in the first example. 

3) Since caching of String objects was important from performance reason this risk was avoided by making String class Immutable. 

4) At the same time, String was made final so that no one can compromise invariant of String class e.g. Immutability, Caching, hashcode calculation etc by extending and overriding behaviours.

Related questions

+1 vote
asked Oct 16, 2020 in JAVA by SakshiSharma
+2 votes
asked May 30, 2020 in JAVA by Robindeniel
...