April 27, 2022

Why String is Immutable in Java

String in Java is immutable that brings us to the question why this decision to design String class as immutable. In this post we’ll see some of the reasons for this design decision.

Java String objects are immutable

Java String class is immutable which means once a String object is created it cannot be changed. When you use a String modification method like concatenation what actually happens is that a new String is created and returned that contains the result of the operation.

For example suppose there is String str-

String str = “Hello”;

That means str refers to the memory location where value "Hello" is stored.

String immutability

Now if you concatenate another value to this String and assign it to the same reference. Since original string can’t be modified because of String being immutable so this concatenation means a new String object is created with the modified value and str starts pointing to this new object.

str = str.concat(" World");
Java String immutable

As you can see str now refers to the modified object and old object is unreferenced and ready to be garbage collected.

Here is another example where concatenation is done but the returned modified string is not assigned to any variable.

public class StringLiteral {
  public static void main(String[] args) {
    String str = "Hello";
    str.concat(" World");
    System.out.println("Value- " + str);
  }
}
Output
Value- Hello

As you can see str is still referring to the original String object.

Why is String immutable in Java

Now when we have seen with examples, what does String is immutable actually means let’s go through the why part.

1- Reduce memory usage- To understand how does String being immutable results in reduced memory usage you’ll have to understand String pool in Java.

String is a special class in Java and also one of the most used too. That is why the concept of constant String pool is used to minimize memory usage.

Whenever any String literal is created (String enclosed in double quotes) JVM scans the String pool for any String having the same value, if found same reference is returned. So, new memory is not allocated for the same string, existing memory is used instead.

Let’s understand with an example. if three Strings are created as follows-

String str1 = “Hello”;
String str2 = “Hello”;
String str3 = “Hello”;

Then the same memory is referenced by all the three objects.

String Java

Now suppose the value of str1 is changed, if the original string itself is changed then what about the other two references. They will also start pointing to the changed value which is not correct. That is why making String immutable ensures that original object can’t be modified.

Pooling strings is possible because of String in Java being immutable and that is how this property contributes in reduced memory usage by Strings.

2- Thread safety- String in Java is immutable so that it can’t be modified once created which in turn means Strings are safe to be used in a multi-threaded environment with out any fear of change.

If a thread changes the value of the shared string even then a new String is created leaving the original as unchanged.

3- Hashcode caching- Another reason that can be given for why String is immutable in Java is that it enables hashcode to be cached for Strings.

Since string once created can’t be modified so the hashcode once calculated for any string can be cached and reused. It is not required to recalculate that hashcode. That makes it very efficient to use String as a key in a hash based data structure like HashMap.

That's all for the topic Why String is Immutable in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like

No comments:

Post a Comment