← Back to Home

String Immutability

String immutability means that once a String object is created, its value cannot be changed. Any operation that appears to modify a String actually creates a new String object, leaving the original unchanged. This is a must-know interview topic and foundational to understanding String Pool, memory behavior, security, and performance.

What Does Immutability Mean?

  • Object state cannot be modified after creation
  • Reference may change, but object content does not
  • Applies strictly to the String class
String s = "Java";
s.concat(" World");
Result:
• "Java" remains unchanged
• "Java World" is created as a new object
          

Proof of String Immutability

String s1 = "Java";
String s2 = s1.concat(" World");
System.out.println(s1); // Java
System.out.println(s2); // Java World
✔ Original string is unchanged
✔ New string object is created
          

Why Strings Are Immutable in Java (Very Important)

1. String Pool Safety

  • String literals are stored in the String Constant Pool
  • Multiple references may point to the same object
  • Immutability prevents unintended changes
String a = "Test";
String b = "Test";
If strings were mutable, changing a would affect b.
          

2. Security

Strings are widely used for:

  • File paths
  • Network connections
  • Class loading
  • User credentials
String path = "/secure/data";
Immutability ensures critical values cannot be altered at runtime.
          

3. Thread Safety

  • Immutable objects are inherently thread-safe
  • No synchronization required
  • Multiple threads can share the same String safely

4. HashCode Caching (Performance)

  • String overrides hashCode()
  • Hash value is cached after first calculation
  • Enables fast lookup in hash-based collections (HashMap, HashSet)

If strings were mutable, cached hash codes would become invalid.

5. Predictable Behavior

  • No side effects
  • Easier debugging
  • Reliable behavior in APIs and frameworks

How Java Enforces String Immutability

1. String Class Is final

  • Cannot be inherited
  • Prevents overriding behavior

2. Internal Character Array Is private final

  • Internal data cannot be accessed or modified directly
  • No setter methods provided

3. Methods Always Return New Objects

s.toUpperCase();
s.replace("a", "o");
s.substring(0, 2);
All return new String objects.
          

Reference Change vs Object Change (Common Confusion)

String s = "Java";
s = s.concat(" World");
• Original object "Java" still exists
• s now points to a new object
Immutability is about object content, not variable reference.
          

String Immutability vs StringBuilder Mutability

StringBuilder sb = new StringBuilder("Java");
sb.append(" World");
• Same object is modified
• No new object created
This is why StringBuilder is faster for frequent modifications.
          

Memory Impact of Immutability

Inefficient Pattern

String s = "";
for (int i = 0; i < 1000; i++) {
    s = s + i;
}
• Creates many temporary objects
• High memory usage
          

Efficient Alternative

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append(i);
}
          

Common Misconceptions

  • concat() modifies the original string ❌
  • String is immutable but reference cannot change ❌
  • Immutability means slower performance ❌
  • final keyword alone makes an object immutable ❌

Common Beginner Mistakes

  • Ignoring immutability and expecting in-place change
  • Using String in loops for concatenation
  • Confusing reference reassignment with object mutation
  • Not understanding memory impact

Interview-Ready Answers

Short Answer

String immutability means a String object cannot be changed once it is created.

Detailed Answer

In Java, String objects are immutable to ensure String Pool safety, thread safety, security, and performance optimizations such as hash code caching. Any modification creates a new String object, leaving the original unchanged.

Key Takeaway

String immutability is a deliberate design choice in Java. It guarantees safety, reliability, and performance, but requires developers to use StringBuilder or StringBuffer for frequent modifications.