Immutable String in Java

String class in Java is immutable. The meaning of immutable is unchangeable or unmodifiable. That is, once we create a string object with value, we are not allowed to perform any changes in that object.

In other words, we cannot modify the value of the string. But if you try to change with a new value, a new string object will be created by storing a new value.

So, we cannot perform any changes with the existing string object. This non-changeable behavior is nothing but an immutability concept in Java.

Java implements this immutability concept to minimize the duplication of string values that tend to exist many times in any application program.

Let’s understand the immutability concept with the help of an example program.

Example:

package stringPrograms; 
public class ImmutabilityTest { 
public static void main(String[] args) 
{ 
 // Creating a sting literal object with content.
    String s = "hello"; 
 
 // Calling concat() method to add string at the end.
    s.concat("world");
    
    System.out.println(s); // It will print "hello" because string is an immutable object. 
 } 
}
Output: 
      hello

Let us understand the explanation of output of the above program by the given below figure.

Why string is immutable in Java

When JVM will execute statement String s = “hello”;, it will create a string object in the string constant pool and store “hello” in it.

When the next statement s.concat(“world”); will be executed by JVM, it will create two new objects because we are trying to modify the original content.

1. First, for every string literal “world”, JVM will create one copy of string object in the string constant pool.

2. The second object will be created in the heap with modified content “hello world”. Since string concatenation is executed at the runtime. Therefore, if a new object is required to create, this new object is always created in the heap area only, not in the string constant pool.

Since this new object is not assigning with any reference variable, therefore, it is called unreferenced object and the garbage collector will automatically remove it from the memory.

Thus, the value of string s is not modified and still, ‘s’ is pointing to “hello” only. Therefore, the result is “hello”. This is the reason, string objects are called immutable in Java.


Key point:

1. String concatenation cannot be resolved at the compile time. It is always executed at runtime. This causes an extra object to be generated.

Why String Objects are Immutable in Java?


String objects are immutable in Java because Java uses the concept of string constant pool. Suppose there are 6 reference variables, and pointing to the same object “Hello world”.

If one reference variable of them changes the value of object from “Hello world” to “Hello”, with this change, all the reference variables will be affected. That’s why string objects are immutable in Java.

The primary advantage of string immutability is that Java compiler can save space in the memory by sharing strings.


Key Points of Immutable String in Java

There are the following key points of immutable strings in Java that you should keep in mind. They are:

(1) String objects are immutable in Java, meaning that once a string object is constructed, its value cannot be changed or updated. Any operation that appears to modify a string actually creates a new string with the desired changes.

(2) Java maintains a pool of string literals known as string constant pool (SCP). When we create a string object, Java checks if an identical string object exists in the pool. If it does, the new string references the existing one, saving memory.

(3) Immutable strings are inherently thread-safe. Multiple threads can access and use the same string object without worrying about concurrent modifications.

(4) Immutable strings are used extensively in cryptographic operations and secure code, as their values cannot be changed accidentally or maliciously.

(5) String concatenation operation using the + operator may seem inefficient due to creating new strings. Java internally optimizes this process using a StringBuilder or StringBuffer to minimize memory and performance overhead.

(6) Since strings are immutable, they can be safely cached and reused without concern for unintended changes.

(7) Immutable strings secure that the value of string remains constant, which simplifies program logic and debugging.

(8) Immutable strings can be compared using the equals() method, as their values are constant. This makes comparing strings for equality straightforward.