Understanding Java String Immutability

The immutability of the String class in Java is a foundational concept that impacts performance, security, and memory optimization. Understanding how and why this design decision was made can help developers better utilize strings in their applications.

1. How Immutability Is Implemented in String

The immutability of String is enforced through a combination of class design, data structure choice, and access control. Here's a simplified version of the core implementation:

public final class String {
    private final char[] content;
    private int cachedHashCode;

    public String(char[] content) {
        this.content = new char[content.length];
        System.arraycopy(content, 0, this.content, 0, content.length);
    }

    public String extractSubstring(int startIndex) {
        char[] newContent = new char[content.length - startIndex];
        System.arraycopy(content, startIndex, newContent, 0, newContent.length);
        return new String(newContent);
    }
}

Key Implementation Details:

  • The content array is private final: This prevents external modification and ensures the array reference cannot be changed after initialization.
  • No methods are provided to modify the internal array: Any operation that appears to change the string (like substring, replace, or concat) actually returns a new String instance.
  • The String class is declared final: This prevents subclassing and potential mutation through overridden methods.

Note: Starting from JDK 9, the internal representation was changed from char\[\] to byte\[\] for better memory efficiency, but the immutability contract remains unchanged.

2. Why String Was Designed as Immutable

This design was chosen not arbitrarily, but to support several critical system behaviors:

(1) Enable String Constant Pool

The JVM maintains a pool of unique string literals to reduce memory usage. Because strings are immutable, identical literals can safely reference the same object:

String a = "hello";
String b = "hello";
System.out.println(a == b); // true

If strings were mutable, changing one reference could inadvertently affect others sharing the same value.

(2) Efficient Hash Code Caching

Since string content never changes, their hash codes can be computed once and reused. This is especially important when using strings as keys in hash-based collectoins like HashMap or HashSet.

(3) Thread Safety

Immutable objects are inherently thread-safe. Multiple threads can reference the same string without synchronization, eliminating race conditions and visibility issues.

(4) Security

Strings often hold sensitive data like passwords or URLs. Immutability prevents unintended modification, reducing the risk of data tampering.

3. Common Misconceptions

  • Misconception: String s = "A"; s = "B"; modifies the string. Reality: This only changes the reference. The original "A" remains in the constant pool.
  • Misconception: Reflection can be used to alter string content. Reality: While technically possible, this breaks the immutability contract and can cause unpredictable behavior in the JVM.

Tags: java string Immutability Memory Management Security

Posted on Sun, 26 Jul 2026 16:24:20 +0000 by nomanoma