Learnitweb

Why String is immutable in Java?

This is a design question. Following points can be given to support this:

1. Security – Consider a case when user is provided access to a particular path. But after getting access, user changes the path. This could be a serious security issue. String is the widely used type of parameter for many Java classes. For example, URL for database connection, opening network connection, path of files and directories etc. If string is not immutable, this can pose a serious security threat. String is also used in class loading mechanism. If string is not immutable then a request to load java.lang.Object can be changed to something malicious like xxx.yyy.zzz.

2. Caching and string pool – String is extensively used in Java applications. To optimize its use, string literals are stored in string pool. This was done so that strings could be shared. To share these safely, they must be of immutable type. If strings are not immutable then this sharing and concept to pool was not possible.

3. Optimization and performance – Since string is immutable, Java caches its hash code. It means hash code is calculated only once and for any repeated requests for hash code, same hash code is returned. Being immutable guarantees same hash code on multiple invocations. This makes it fast and safe to use string as key in HashMap.

4. Multithreading – Since string is immutable, it can be safely shared between threads. Immutablity makes String instance thread-safe and there is no need to synchronize string operation externally. This results in more readable code.