Why String is Immutable in Java

Why string is immutable in Java? This question remains one of the most popular in the Java domain. We know that String is immutable but why it is developed as immutable? Most of the Java classes and the normal Java classes created by us are mutable in nature then why String was developed explicitly as immutable? There are many reasons behind this but the main reasons are:- design, efficiency, and security.

Security

Java applications contain much sensitive information like network connections, database connection URLs, username, password, and e.t.c. Most of the time these pieces of information are stored in String. Since the string is immutable therefore once an object is created we can’t modify it.

Let us understand it through an example:- In JDBC to create a connection we need a database URL, username, and password as String type. If any of them is incorrect then a connection object will be created.

String url = "jdbc:oracle:thin:@localhost:1521:knowprogram";
String user = "scott";
String password = "tiger";
// establish the connection
Connection con = DriverManager.getConnection(url, user, password);

Now, assume before establishing the connection we are calling the user.toUpperCase(); It will generate result “SCOTT”. Since String is immutable, therefore, the result will be stored in another string object, not the current object. Due to this reason, the remaining code will not be affected.

If String was developed as mutable then after calling user.toUpperCase(); the result will be stored in the same object. While establishing a connection username will not match with the real database username, and hence connection will not be established.

This is a simple example, there are many situations where the mutable nature of string may create several problems.

Synchronization and Concurrency

By developing classes as immutable, by default this nature makes them threadsafe. Hence it solves all synchronization issues and no need to write extra code.

After immutable object creation, it can’t be modified by any operation which makes every immutable object as threadsafe by default. Due to this immutable nature, String objects can be shared by multiple threads and even if it is getting manipulated by many threads it will not change its value.

Class Loading

While class loading string is used as an argument. If String is mutable then after modification result will be stored to the same String object and it could lead to the wrong class being loaded.

String str = "Example";

str.toUpperCase(); 
// no effect on current string object

Class.forName(str);

Since the String class is immutable, therefore “str” object will not be modified. If it is a mutable object then the result will be “EXAMPLE”, and leads to load a wrong class or get an exception message.

HashCode Caching

If we are going to perform any hashing-related operations on our object we must override the hashCode() method and try to generate an accurate hashcode by using the state of the object. If the object’s state is getting changed which means its hashcode should also change.

Since String is immutable therefore hashcode value will not change which gives the String class an opportunity to cache its hashcode during object creation. Hashcode doesn’t need to be calculated again and again.

String object caches its hashcode at the time of object creation and makes it a great candidate for hashing-related operations. This is why String is the most suitable candidate to be used as HashMap keys.

import java.util.Hashtable;

public class Test {
   public static void main(String[] args) {
      Hashtable<String, String> ht = new Hashtable<String, String>();
      String key = "Name";
      String value = "Know Program";
      ht.put(key, value);

      key.toUpperCase(); // no effect

      Object obj = ht.get(key);
      System.out.println(obj);
   }
}

Output:-

Know Program

From this program, the Hashtable object contains the following data:-

KeyValue
NameKnow Program

When we call ht.get(key) then it will use “key” to fetch the corresponding value. If it is not available then we will get null.

If String is mutable then key.toUpperCase() change its data to “NAME”. Now, while retrieving using the get() method it will search for the “NAME” which is not available in the Hashtable, therefore we will get null.

Since Hashtable is immutable therefore after modification result is stored in a new string object, and the existing object is not affected. If we assign the new string object to the existing reference variable then we will get null.

key = key.toUpperCase(); 
// new object reference

Object obj = ht.get(key);
System.out.println(obj);

Output:-

null

The string is given as immutable for storing string object as a key in map collection object and further retrieving the mapped key-value even though data is modified. The string object is given as immutable to store as a key in the map object. Whereas StringBuffer and StringBuilder are given as mutable and not meant for storing in map object as a key.

The string connection pool is also considered as one of the reasons why String is Immutable in Java. But String is not given as immutable because of pooling. String object is immutable therefore pooling is implemented.

Similar Articles like “Why String is Immutable in Java?”:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *