Java String intern() Method Example

  • Java String intern() method returns the canonical representation of the string.
  • When we invoke intern() method on a string, if the string pool already has a string having the same value, then the reference of that string is returned. Otherwise, a new string with the same value is created in the pool and its reference is returned.
  • Java String intern() is a native method.
  • For two strings s1 and s2, s1.intern() == s2.intern() is true if and only if s1.equals(s2) is true.
  • If we call intern() method on a string literal, the same reference is returned because the string is already in the pool.
  • The intern() method guarantees that the string returned is from the pool.

Java String intern() Method Example

jshell> String s1 = "Hello";
s1 ==> "Hello"

jshell> String s2 = new String("Hello");
s2 ==> "Hello"

jshell> s1 == s2
$24 ==> false

jshell> String s3 = s2.intern();
s3 ==> "Hello"

jshell> s1 == s3
$26 ==> true
Java String Intern Method Example
Java String intern() Method Example

String intern() Example Explanation

Let’s understand what is happening in each of the above statements.

  1. String s1 is created in the string pool. It’s a string literal.
  2. String s2 is created in the heap space because we are using the new operator.
  3. s1 == s2 returns false because they are referring to different objects.
  4. When we are calling s2.intern(), a reference from the string pool is returned where the string value is “Hello”. Since string pool contains only unique values and we already have s1 with the same value, the same reference is returned.
  5. We are assigning the interned string to a new string variable s3.
  6. s1 == s3 returns true because both of them are referring to the same string object in the pool.

Why do we need the String intern() Method?

  • If you have a lot of strings created using the new operator, it makes sense to call intern() method to save memory space.
  • Generally, we use the equals() method for string equality. But, it can be slow if the string size is huge. We can call intern() method to make sure that the string is part of the pool and then use == operator for equality check. Since == operator only checks the reference, it’s much faster than the equals() method.
  • String intern() method is useful when we are getting a string object from other APIs. For example, StringBuilder and StringBuffer toString() method uses the new operator to create the string. If it’s huge and we want to test for equality, calling intern() and then using == operator would be better.

Reference: