In interview, you may encounter this question. Let’s see why String is immutable in java.
- As we know String uses the string constant pool for the memory location. Suppose we have multiple reference variables, all are pointing to the same object, if String is not immutable and we change the value of any reference then all others reference will get affected. Let’s see in below diagram –
Suppose now we are doing s1 = “ram” and if String is not immutable, s2 and s3 will start pointing to “ram”. As of now, we have three objects, it might possible we have a hundred or thousands of objects, all will start to point “ram” instead of “rakesh”. That’s the very big problem.
- Since String is immutable, it is safe to use in multithreading. This avoids the use of synchronization for thread safety, String is implicitly thread safe in nature.