Phase 8 of 20 · Topic 8.1

String Constant Pool (SCP) & Immutability Architecture

1Concept

String objects in Java are immutable. The JVM maintains a special heap region called the String Constant Pool (SCP). When a string literal is created (`String s = "Java"`), the JVM checks the pool: if it exists, the existing reference is returned; otherwise, a new instance is created. Immutability ensures thread-safety, security in network/DB connections, and hashcode caching.

2Architecture Diagram

Heap Memory:
  String s1 = "Tech"; ---
                         \---> [ String Constant Pool ]
  String s2 = "Tech"; --->      [ "Tech" ] (Single shared instance)
  String s3 = new String("Tech"); ---> [ Separate Heap Object ]

3Code Example

Core Java
public class StringPoolDemo {
    public static void main(String[] args) {
        String s1 = "Enterprise";
        String s2 = "Enterprise";
        String s3 = new String("Enterprise");

        System.out.println("s1 == s2 (Same pool reference): " + (s1 == s2));
        System.out.println("s1 == s3 (Heap vs Pool instance): " + (s1 == s3));
        System.out.println("s1.equals(s3) (Content equality): " + s1.equals(s3));
    }
}

4Expected Output

s1 == s2 (Same pool reference): true
s1 == s3 (Heap vs Pool instance): false
s1.equals(s3) (Content equality): true

5Key Takeaways

  • String literals share references in the String Constant Pool; `new String()` forces new heap allocation.
  • String immutability allows caching `hashCode()` value, speeding up HashMap lookups.
  • Java 9+ Compact Strings store LATIN-1 chars as 1-byte arrays (`byte[]`) instead of UTF-16 2-byte arrays.