Why String is Immutable in Java?

Why String is immutable in Java is one of the popular interview questions. The string is one of the most used classes in any programming language. We know that String is immutable and final in Java. Java runtime maintains a String pool that makes it a special class.

Benefits of String Immutability

String pool is possible only because String is immutable in Java. This way Java Runtime saves a lot of heap space because different String variables can refer to the same String variable in the pool. If String would not have been immutable, then String interning would not have been possible because if any variable would have changed the value, it would have been reflected in the other variables too.

If String is not immutable then it would cause a severe security threat to the application. For example, database username, password are passed as String to get database connection and in socket programming host and port details passed as String. Since String is immutable, its value can’t be changed otherwise any hacker could change the referenced value to cause security issues in the application.

Since String is immutable, it is safe for multithreading. A single String instance can be shared across different threads. This avoids the use of synchronization for thread safety. Strings are implicitly thread-safe.

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.

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 the key in a Map and its processing is faster than other HashMap key objects. This is why String is the most widely used as HashMap keys.

Conclusion

Above are some of the reasons I could think of that shows benefits of String immutability. It’s a great feature of the Java String class and makes it special. Read this post to know how to write your own immutable class.

You can checkout more Java String examples from our GitHub Repository.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

centron Managed Cloud Hosting in Deutschland

Extended Security Updates for Windows Server

Security
Extended Security Updates for Windows Server Extended Security Updates (ESU) for Windows Server include security updates and bulletins rated critical and important. Content1 How you get ESUs depends on where…