Java.Core.What does the intern() method do in the String class?

What Does the intern() Method Do in the String Class?

The intern() method in the Java String class is used to store a string in the String Pool and return a reference to the pooled instance. This ensures that identical strings share the same memory reference, optimizing memory usage.


How Does intern() Work?

1. If the String Already Exists in the Pool

  • If a string with the same content is already present in the String Pool, intern() returns a reference to that pooled instance.

2. If the String is Not in the Pool

  • If the string does not exist in the pool, intern() adds it to the pool and returns the reference.

Example: Using intern()

public class StringInternExample {
    public static void main(String[] args) {
        String s1 = "Java"; // Stored in the String Pool
        String s2 = new String("Java"); // Created in Heap
        
        System.out.println(s1 == s2); // false (different objects)

        // Interning s2 to store it in the String Pool
        String s3 = s2.intern(); 

        System.out.println(s1 == s3); // true (both refer to the same pooled string)
    }
}

Explanation:

  1. "Java" (a string literal) is automatically stored in the String Pool.
  2. new String("Java") creates a new object in the heap, not in the pool.
  3. s2.intern() stores "Java" in the pool (if not already present) and returns the reference.
  4. s1 == s3 is true because both refer to the same pooled object.

Why Use intern()?

1. Saves Memory

  • By ensuring that identical strings share the same reference, intern() reduces memory usage.
String s1 = new String("Optimization").intern();
String s2 = "Optimization";

System.out.println(s1 == s2); // true (both refer to the pooled object)

Benefit: No duplicate "Optimization" strings in memory.


2. Improves Performance in String Comparisons (== vs. .equals())

  • == (reference comparison) is faster than .equals() (content comparison).
  • Interning allows fast reference-based comparisons.
String a = new String("Test").intern();
String b = "Test";

System.out.println(a == b); // true (same reference)
System.out.println(a.equals(b)); // true (same content)

Benefit: Faster string comparisons when dealing with large amounts of text.


Limitations of intern()

1. May Increase String Pool Size

  • If you intern too many unique strings, they stay in the pool indefinitely (not garbage collected).
  • Example of memory overhead: javaCopyEdit
for (int i = 0; i < 1_000_000; i++) {
    String s = ("String" + i).intern(); // Every unique string is stored permanently
}
  • 🚨 Risk: Can lead to high memory usage.

2. Slower for Large Strings

  • Interning large strings (e.g., long paragraphs) is inefficient.
  • String Pool is optimized for smaller, frequently used strings.

Example:

String largeString = new String(new char[100000]).replace('\0', 'X').intern();

🚨 Risk: Large strings waste memory in the pool.


Key Takeaways

FeatureDescription
Stores Strings in String PoolEnsures identical strings share the same reference.
Reduces Memory UsageNo duplicate string objects in heap.
Improves Performance== comparison is faster than .equals().
May Cause Memory IssuesToo many interned strings increase String Pool size.
Not Ideal for Large StringsLarge strings in the pool can waste memory.

When Should You Use intern()?

Use intern() when:

  • You have many repeated strings (e.g., configuration keys, database column names).
  • You need fast == comparisons.
  • You are optimizing memory usage in large applications.

Avoid intern() when:

  • You deal with large, unique strings (e.g., file contents, logs).
  • You don’t need reference-based comparisons.

Conclusion

  • intern() helps save memory and improve performance by storing unique strings in the String Pool.
  • However, excessive interning can cause memory overhead.
  • Use it wisely for frequently used strings.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.