Phase 8 of 20 · Topic 8.4

String Interning with String.intern() & Heap Optimization

1Concept

The `String.intern()` method moves heap string instances into the String Constant Pool. If the pool already contains an equal string, the canonical pool reference is returned. This can reduce memory footprint by 50%+ in data-heavy applications parsing millions of duplicate strings (e.g. country codes, state names).

2Architecture Diagram

[ Heap String: "US" (10,000 instances) ]
                     |
             .intern() invoked
                     v
[ String Constant Pool: single canonical "US" ] ---> Memory footprint reduced by 99%!

3Code Example

Core Java
public class StringInternDemo {
    public static void main(String[] args) {
        String heapStr = new String("CanonicalData");
        String internedStr = heapStr.intern(); // Canonical pool reference
        String literalStr = "CanonicalData";

        System.out.println("heapStr == literalStr:     " + (heapStr == literalStr));
        System.out.println("internedStr == literalStr: " + (internedStr == literalStr));
    }
}

4Expected Output

heapStr == literalStr:     false
internedStr == literalStr: true

5Key Takeaways

  • Interning strings allows fast reference comparison (`==`) instead of character-by-character `.equals()`.
  • Do not blindly intern dynamic unconstrained strings (e.g. user input); it can bloat the JVM String table.
  • G1GC provides automatic String Deduplication (`-XX:+UseStringDeduplication`).