Sitemap
Uma Charan Gorai

Uma Charan Gorai

Application Architect @IBM

Why String is immutable in Java

3 min readNov 23, 2024
Press enter or click to view image in full size

In Java, String is immutable because once a String object is created, its state (value) cannot be changed. Any modification to a String results in the creation of a new String object rather than altering the existing one. This immutability is implemented for several reasons:

Reasons for String Immutability

1. Thread Safety:
Since String objects are immutable, they can be shared between multiple threads without synchronization. This makes String inherently thread-safe, reducing the need for explicit synchronization in multi-threaded environments.

2. Security:
Strings are used in sensitive areas such as file paths, network connections, and database usernames/passwords. If String were mutable, malicious code could alter its content, leading to security vulnerabilities.

3. Performance and Caching:
Strings are cached in the String Pool to optimize memory usage. If String were mutable, the same String object in the pool could be changed, affecting other references.
Immutability allows reusing strings without creating duplicate objects.

4. HashCode Consistency:
Strings are commonly used as keys in hash-based collections like HashMap. Immutability ensures that the hashCode value of a String remains consistent, making it reliable as a key.

Example to Illustrate String Immutability

public class StringImmutabilityExample {
public static void main(String[] args) {
// Original String
String str1 = "Hello";
System.out.println("Original String: " + str1);
// Attempt to modify the String
String str2 = str1.concat(" World");
// Check if the original string is modified
System.out.println("After Concatenation:");
System.out.println("Original String: " + str1); // Still "Hello"
System.out.println("New String: " + str2); // "Hello World"
// Verifying different memory locations
System.out.println("Are str1 and str2 the same object? " + (str1 == str2));
}
}

Output:
Original String: Hello
After Concatenation:
Original String: Hello
New String: Hello World
Are str1 and str2 the same object? false

Get Uma Charan Gorai’s stories in your inbox

Join Medium for free to get updates from this writer.

Explanation

1. When str1.concat(“ World”) is called:
a. A new String object is created with the value “Hello World”.
b. The original String (str1) remains unchanged.
2. The reference str2 points to the new String object, while str1 still points to the original “Hello”

Proof of Immutability

Here’s an example that demonstrates the String Pool and how immutability works with caching:

public class StringPoolExample {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
// s1 and s2 refer to the same object in the String pool
System.out.println("s1 == s2: " + (s1 == s2)); // true
// Modifying s1 creates a new String object
s1 = s1.concat(" Programming");
System.out.println("Modified s1: " + s1); // "Java Programming"
System.out.println("s2: " + s2); // "Java"
// s1 and s2 now refer to different objects
System.out.println("s1 == s2: " + (s1 == s2)); // false
}
}

Output:
s1 == s2: true
Modified s1: Java Programming
s2: Java
s1 == s2: false

Conclusion

The immutability of String in Java provides thread safety, security, consistent hash codes, and efficient memory management through String Pooling. When working with String, it is important to understand that any modification results in a new object being created.

For scenarios where mutability is required, Java provides the StringBuilder and StringBuffer classes, which are mutable alternatives to String. Let me know if you’d like to explore those as well!

--

--