Java String intern()
Let’s try to understand intern() method with a simple program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.journaldev.string; public class StringIntern { public static void main(String args[]) { String s1 = new String("abc"); // goes to Heap Memory, like other objects String s2 = "abc"; // goes to String Pool String s3 = "abc"; // again, goes to String Pool // Let's check out above theories by checking references System.out.println("s1==s2? " + (s1 == s2)); // should be false System.out.println("s2==s3? " + (s2 == s3)); // should be true // Let's call intern() method on s1 now s1 = s1.intern(); // this should return the String with same value, BUT from String Pool // Let's run the test again System.out.println("s1==s2? " + (s1 == s2)); // should be true now } } |
Output:
1 2 3 4 5 |
<span style="color: #008000;"><strong><code> s1==s2? false s2==s3? true s1==s2? true </code></strong></span> |
String intern() Example Explanation
- 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”. - 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”.
- In the first print statement, s1 and s2 are referring to different objects. Hence s1==s2 is returning
false
. - In the second print statement, s2 and s3 are referring to the same object in the pool. Hence s2==s3 is returning
true
. - 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. - Notice that we are calling
s1 = s1.intern()
, so the s1 is now referring to the string pool object having value “abc”. - 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