0
0
JavaConceptBeginner · 3 min read

Java String intern() Method: What It Is and How It Works

The intern() method in Java String returns a canonical representation of the string object. It ensures that all strings with the same content share a single instance from the string pool, saving memory and allowing fast equality checks.
⚙️

How It Works

Imagine you have many copies of the same word written on different pieces of paper. Instead of keeping all those papers, you keep just one master copy and refer to it whenever needed. The intern() method works similarly for strings in Java.

When you call intern() on a string, Java checks a special place called the "string pool" to see if an identical string already exists. If it does, Java returns the reference to that existing string. If not, it adds the string to the pool and returns its reference. This way, strings with the same content share one object, saving memory and speeding up comparisons.

💻

Example

This example shows how intern() makes two strings with the same content share the same reference.

java
public class InternExample {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");

        System.out.println(s1 == s2); // false, different objects

        String s3 = s1.intern();
        String s4 = s2.intern();

        System.out.println(s3 == s4); // true, same pooled object
    }
}
Output
false true
🎯

When to Use

Use intern() when you expect many strings with the same content and want to save memory by sharing one copy. It is helpful in programs that handle lots of repeated strings, like parsing large text files or processing user input.

Also, since interned strings share references, you can use == to compare them quickly instead of equals(), which checks content. But be careful: excessive interning can slow down your program if overused.

Key Points

  • intern() returns a shared string from the string pool.
  • It saves memory by avoiding duplicate string objects.
  • Comparing interned strings with == is faster than equals().
  • Use it wisely to balance memory and performance.

Key Takeaways

The intern() method returns a shared string instance from Java's string pool.
It helps save memory by reusing strings with the same content.
Interned strings can be compared with == for faster checks.
Use intern() when handling many repeated strings to optimize memory.
Avoid overusing intern() as it may impact performance negatively.