Skip to main content
InterviewHubPRO
Section Overview
Q21

Question 21 of 50

Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

42%
Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

What is the String Constant Pool and how does String.intern() affect heap memory?

senior LevelCode ExampleMemory ManagementSystem DesignData Structures

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 new String object in normal heap memory.
  • s2.intern() -> Queries the pool; returns the canonical reference from the pool.
java
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.