What is the String Constant Pool and how does String.intern() affect heap memory?
In Simple Words:
The String Constant Pool is a specialized hashtable located in the Java Heap memory. When a string literal like "hello" is declared, the JVM checks if an identical string already exists in the pool. If found, it returns the cached reference; otherwise, it creates and stores a new entry.
Key Differences:
String s1 = "test";-> Reuses pool reference ($O(1)$ memory).String s2 = new String("test");-> Forces creation of a distinct newStringobject in normal heap memory.s2.intern()-> Queries the pool; returns the canonical reference from the pool.
String a = "hello";
String b = new String("hello");
System.out.println(a == b); // false (different heap memory addresses)
System.out.println(a == b.intern()); // true (intern points to constant pool reference)
Production Warning on String.intern():
The pool is managed by an internal native hashtable (-XX:StringTableSize). Interning millions of unique, high-cardinality strings (like UUIDs) can cause massive lock contention and garbage collection pauses.