Course contentsShow
← Java
Lesson 2178 of 2,87043. String Handling in DepthFree lesson

The intern() Method

Using String.intern() to manually add dynamically created strings to the pool and retrieve canonical instances.

The intern() Method

You'll learn how to use String.intern() to manually add dynamically created strings to the intern pool and retrieve their canonical instances.

What intern() Does

While string literals are automatically placed in the intern pool, strings created at runtime (through concatenation, StringBuilder, user input, etc.) normally live in regular heap memory. The intern() method lets you manually add these strings to the pool or retrieve the existing pooled version if one already exists.

When you call myString.intern(), Java checks the intern pool:

  • If an equal string already exists in the pool, intern() returns a reference to that pooled instance
  • If no match exists, the string is added to the pool, and a reference to it is returned

Why Use It?

Think of intern() as a deduplication tool. If your application processes thousands of strings with many duplicates (like repeated city names or status codes), interning them can save memory and enable fast == comparisons instead of slower .equals() calls.

Basic Example

String s1 = "hello";              // literal, already interned
String s2 = new String("hello");  // new heap object
String s3 = s2.intern();          // retrieves pooled "hello"

System.out.println(s1 == s2);     // false (different objects)
System.out.println(s1 == s3);     // true (both reference pool)

Practical Scenario

String userInput = readFromDatabase(); // "SUCCESS"
String interned = userInput.intern();  // pool the value

if (interned == "SUCCESS") {  // fast identity check
    // handle success
}

Key Takeaway:
String.intern() manually adds dynamically created strings to the intern pool, enabling memory savings and fast identity comparisons by ensuring only one instance of each unique string exists in the pool.