String is immutable for several reasons

Design Strings are created in a special memory area in java heap known as “String Intern pool”. If the String is not immutable, changing the String with one reference will lead to the wrong value for the other references.

Security: String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. Mutable strings could cause security problem in Reflection too, as the parameters are strings.

Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.

Caching: Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys. Above are some of the reasons I could think of that shows benefits of String immutability. It’s a great feature of Java String class and makes it special.

Class loading: Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader. For example, think of an instance where you are trying to load java.sql.Connection class but the referenced value is changed to myhacked.Connection class that can do unwanted things to your database.

substring(), concat(), replace() etc are internally use String constructor for creating new string object.

Comments are closed.