Java String intern() With Examples

Java String intern() is a native method. When the intern() method is invoked on a String object, if the String Pool already has a String with the same value, then the reference of String from the Pool is returned. Otherwise, this string object is added to the pool and the reference is returned.

java-string-internJava String Intern

Java String intern()

Let’s try to understand intern() method with a simple program.

Output:

String intern() Example Explanation

  1. When we are using new operator, the String is created in the heap space. So “s1” object is created in the heap memory with value “abc”.
  2. When we create string literal, it’s created in the string pool. So “s2” and “s3” are referring to string object in the pool having value “abc”.
  3. In the first print statement, s1 and s2 are referring to different objects. Hence s1==s2 is returning false.
  4. In the second print statement, s2 and s3 are referring to the same object in the pool. Hence s2==s3 is returning true.
  5. Now, when we are calling s1.intern(), JVM checks if there is any string in the pool with value “abc” is present? Since there is a string object in the pool with value “abc”, its reference is returned.
  6. Notice that we are calling s1 = s1.intern(), so the s1 is now referring to the string pool object having value “abc”.
  7. At this point, all the three string objects are referring to the same object in the string pool. Hence s1==s2 is returning true now.

Please watch the below YouTube video for better clarity about the intern() method.

Reference: API Doc

By admin

Leave a Reply