Why are Strings Immutable in Java?

Java Strings are immutable by default. The immutability of Strings helps in providing features such as caching, security, fast performance and better memory utilization. This tutorial discusses how the immutability of Strings helps in achieving these features.

1. What is an Immutable Class?

Let us start with immutability itself. An immutable object is an object whose state is guaranteed to remain unchanged over its entire lifetime. It means that the object’s state, once initialized, can never be changed anyway.

Java also has immutable classes, which are primarily String and wrapper classes. Read more about how to create an immutable class.

2. Strings in Action

Memory in Java is divided into three parts, i.e., Heap, Stack, and String Pool. The String Constant Pool is a special area used for the storage of string literals.

When we create a String, a String object is searched in the string pool with exact same content. If an existing String object is found, then its reference is pointed to the new variable, thus, effectively, the existing object is reused for the new string declaration as well. It helps in minimizing memory usage due to multiple strings with the same content.

String str1 = "value";
String str2 = "value";
String str3 = "value";

The above program creates 3 String type variables, all pointing to the same object in the spring pool area. All future Strings with content “value” will point to the same object in the heap and thus save the memory.

When we modify a string, a new string is created in the pool with modified content. The existing object is never changed.

str3 = "test";

When there is no reference variable pointing to a string object in the pool, the object is garbage collected. In this way, a string, once created, never gets changed.

3. Advantages of Immutable Strings

Let us now understand how the above-discussed immutability helps in runtime.

3.1. Application and Data Security

The first and undeniably most important reason is security. Well, it is not only about our application but even for JDK itself. Java class loading mechanism works on class names passed as parameters, then these classes are searched in the classpath.

In the following program, we are loading the SQL server driver by its class name. Imagine for a moment, Strings were mutable, then a bad actor could have changed the driver name, loaded a bad driver class in runtime and, with very little effort, hacked in the application.

public static final String DRIVER_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

Similarly, bad actors can change the SQL statements and perform SQL injection in runtime. Immutability ensures that such modifications never occur.

3.2. Improved Performance

The immutability of String class gives is the basis of the string pool. Without immutability, there is no difference between a normal heap memory and a string pool.

As discussed in the previous section, string pools help achieve improved memory utilization, and, thus, better performance.

3.3. Thread Safety

Immutable objects are automatically thread-safe in multi-threaded applications. If something can’t be changed, then even a Thread can not change it. Simple thing!

As String class is a main building block of the java programming language, because of its use in the classloading mechanism, it is mandatory to prevent the String class from being dirty in case of multiple threads. Immutability does the magic here.

3.4. Caching

The caches are generally implemented as key-value pairs, similar to Map implementation in Java. The cache keys are generally stored as Strings for quick lookups.

Consider if we could change a key after its associated value is stored in the cache. There will no possible way to retrieve the value thereafter until we build the same key accidentally.

The immutability of strings guarantees that cache keys will never get changed. That is why strings are the most used keys in caches and maps in Java.

4. Conclusion

We can conclude from the above discussion that string immutability helps in achieving the required safety and performance in a Java application.

Happy Learning !!

Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.