According to String#intern(), intern
method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string
As you said, that string intern()
method will first find from the String pool, if it finds, then it will return the object that points to that, or will add a new String into the pool.
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Hello".intern();
String s4 = new String("Hello");
System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//true
System.out.println(s1 == s4.intern());//true
The s1
and s2
are two objects pointing to the String pool "Hello", and using "Hello".intern()
will find that s1
and s2
. So "s1 == s3"
returns true, as well as to the s3.intern()
.
By using heap object reference if we want to get corresponding string constant pool object reference, then we should go for intern()
String s1 = new String("Rakesh");
String s2 = s1.intern();
String s3 = "Rakesh";
System.out.println(s1 == s2); // false
System.out.println(s2 == s3); // true
Pictorial View
Step 1: Object with data 'Rakesh' get created in heap and string constant pool. Also s1 is always pointing to heap object.
Step 2: By using heap object reference s1, we are trying to get corresponding string constant pool object referenc s2, using intern()
Step 3: Intentionally creating a object with data 'Rakesh' in string constant pool, referenced by name s3
As "==" operator meant for reference comparison.
Getting false for s1==s2
Getting true for s2==s3
Hope this help!!