Understanding String Interning in Java

String interning in Java is a process which optimizes memory consumption by storing only one copy of each unique string value. Instead of creating a new object every time a string is defined, Java checks if the string already exists in a pool. If it does, it returns a reference to the existing string; if not, it adds the string to the pool.

The String Pool

Java maintains a special memory area called the “string pool” where interned strings are stored. This pool ensures that multiple references to the same string literal point to the same memory location.

String s1 = "Coder Sathi!";
String s2 = "Coder Sathi!";
System.out.println(s1 == s2); // true

In the example above, both s1 and s2 point to the same string in the pool. This behavior is possible due to string interning.

Why Use String Interning?

String interning offers several advantages:

  1. Memory Efficiency: By reusing string objects, you reduce memory usage, which is essential in memory-constrained environments.
  2. Faster String Comparison: Comparing interned strings using == is faster than using .equals() because it involves comparing references, not characters.
  3. Consistency: String interning ensures that the same string literal is always represented by the same object, enhancing predictability.

How to Intern Strings in Java

In Java, strings can be interned using the intern() method. This method returns a canonical representation of the string.

String s1 = new String("Coder Sathi!").intern();
String s2 = "Coder Sathi!";
System.out.println(s1 == s2); // true

In this example above, s1 is explicitly interned, and it’s identical to s2.

If we take an example of the same code above without using the intern() method then the output will be false.

 String s1 = new String("Coder Sathi!");
String s2 = "Coder Sathi!";
System.out.println(s1 == s2); // false

String Interning Best Practices

  • Intern strings sparingly: String interning can lead to increased memory consumption if used excessively.
  • Prefer using string literals: When possible, use string literals (e.g., "Hello") rather than creating new strings with the new keyword.
  • Use equals() for content comparison: While == is useful for reference comparison, it’s safer to use .equals() when comparing string contents.

Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#intern–