Q7: Why are Java Strings immutable and how does the String Constant Pool work?
Strings in Java are final and immutable for Security (db connections, network parameters), Thread-Safety (shared without synchronization), and Caching.
The String Constant Pool (SCP) is a special heap area. String literals are stored here and shared across the JVM to reduce duplicate memory footprint.
String Literal vs New Instance Allocation
String s1 = "Java"; // Stored in String Pool
String s2 = "Java"; // Reuses pooled instance
String s3 = new String("Java"); // Explicitly creates new Heap object
System.out.println(s1 == s2); // true (same reference)
System.out.println(s1 == s3); // false (different heap memory addresses)Literals reuse SCP instances; string construction via new allocates distinct heap instances.
Key Takeaways
Immutability enables safe sharing, hash code caching, and thread safety.
String literals are stored in the String Constant Pool inside heap memory.
Knowledge Check
Where is the String Constant Pool located in modern Java architectures (Java 7+)?