Saturday, November 28, 2020

Why Java String is Immutable

String in Java is immutable which means once you create a String object the content of that string cannot be modified. If you modify that string then a new String object is created with the modified value, leaving the original string intact.

For example-

String str = "Test";
str.concat(" String");
System.out.println("Original String- " + str);

Output

Original String- Test

As you can see in String str another String is concatenated but that creates a new String object, original string can’t be altered as String is immutable. Since the new string “Test String” is not referenced so it is eligible for garbage collection.

Java String immutable

Even though you can’t modify a String but you can change the reference, so following is valid.

String str = "Test";
str = str.concat(" String");
System.out.println("Original String- " + str);

Output

Original String- Test String

As you can see now str references the modified string.

String reference change

Why is String immutable in Java

Why is String immutable in Java is one of the frequently asked String interview question. Here are some of the points to explain the reason behind the design decision to make String immutable in Java.

1. Usage of constant String pool- Since String class is one of the most used classes in Java so certain optimizations have been done to make String class more efficient. One of that optimization is to use String Pool in Java so that the String objects having same value share the same memory rather than creating new objects. That helps in reducing memory usage of string objects. This usage of String pool is possible only because String is immutable in Java.

Consider the scenario where two or more objects are sharing a reference in string pool. If one of those objects is modified then a new object is created because of String immutability leaving the original object intact to be shared by other objects.

String pool

Here both str1 and str2 are sharing the reference, now value of str2 is modified. Because of String immutability a new object is created, if it were not the case and original value was modified then str1 would reference a changed value which is not correct.

2. Making Strings thread safe- Making String immutable in Java also makes String objects thread safe. String objects can be shared among multiple threads even if any thread modify the original object it will get a new object because of immutability, so original object remains intact.

3. Good candidate as hash keys- Making String immutable in Java also makes them a good candidate as a hash key in hash based data structures like HashMap. Since String can’t be modified once value is assigned to it that means hash code once calculated for any string also won’t change. This facilitates the caching of hashcode rather than calculating hashcode each time, making hashing more efficient.

Drawback of String immutability in Java

One drawback of String immutability is any modification results in creation of new object. Thus a code as given below results in creation of many intermediate objects which are later discarded.

String str = "Test";
str = str.concat(" String").concat("Another").concat("String");

In the case string is modified frequently consider using StringBuffer or StringBuilder classes which are mutable.

That's all for this topic Why Java String is Immutable. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. How to Create Immutable Class in Java
  2. String Vs StringBuffer Vs StringBuilder in Java
  3. String join() Method And StringJoiner Class in Java
  4. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  5. Find All Permutations of a Given String Java Program

You may also like-

  1. Convert String to float in Java
  2. Java Variable Types With Examples
  3. Java do-while Loop With Examples
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Externalizable Interface in Java
  6. Java Collections Interview Questions And Answers
  7. Magic Methods in Python With Examples
  8. Sending Email Using Spring Framework Example

No comments:

Post a Comment