Java String Immutability Explained: Why Strings Can’t Change

What Does “Immutable” Mean?

In Java, immutable means once a String object is created, its value cannot be modified. Any operation that appears to change the String (e.g., concatenation, substring) actually creates a brand-new String object.

Example: Immutability in Action

String original = "Hello";  
String modified = original.concat(" World");  

System.out.println(original);  // "Hello" (unchanged)  
System.out.println(modified);  // "Hello World" (new object)  

Why Are Java Strings Immutable?

Java’s designers chose immutability for Strings to ensure:

  1. Security: Safe usage in network calls, file paths, and hash-based collections (e.g., HashMap keys).
  2. Thread Safety: Immutable objects can be shared across threads without synchronization.
  3. Performance: Caching hash codes and enabling String Pool optimization.
  4. Integrity: Prevents accidental changes in sensitive contexts (e.g., database URLs).

Pros and Cons of String Immutability

Advantages

✅ Safety: No risk of unintended side effects when passing Strings between methods.
✅ Hash Caching: Hash code is computed once and reused, improving HashMap performance.
✅ Memory Efficiency: Enables String Pool reuse of literals.

Disadvantages

❌ Overhead: Frequent modifications create temporary objects, increasing garbage collection.
❌ Workarounds Needed: Requires StringBuilder or StringBuffer for heavy mutations.

How Immutability Affects Performance

The Cost of String Concatenation

Avoid using + in loops – it creates intermediate String objects:

// Inefficient: Creates 10 String objects!  
String result = "";  
for (int i = 0; i < 10; i++) {  
    result += i;  
}  

// Efficient: Uses mutable StringBuilder  
StringBuilder sb = new StringBuilder();  
for (int i = 0; i < 10; i++) {  
    sb.append(i);  
}  
String result = sb.toString();  

Output:

0123456789

Common Misconceptions

Myth: “Calling toUpperCase() changes the original String.”

Reality: It returns a new String; the original remains untouched.

String s = "java";  
s.toUpperCase();  // Does nothing!  
System.out.println(s);  // "java"  

String upper = s.toUpperCase();  // Correct approach  
System.out.println(upper);  // "JAVA"  

FAQs

Can I make a String mutable?

No – but StringBuilder/StringBuffer provide mutable alternatives.

Does immutability slow down Java programs?

Not inherently – poor usage (e.g., loops with +) causes issues. Optimize with StringBuilder.

Up NextCommon String Operations: Learn essential methods like substring()indexOf(), and trim().

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments