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 object will be added in String pool and the reference of this String is returned.
So i tried this:
String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();
if ( s1 == s2 ){
System.out.println("s1 and s2 are same"); // 1.
}
if ( s1 == s3 ){
System.out.println("s1 and s3 are same" ); // 2.
}
I was expecting that s1 and s3 are same
will be printed as s3 is interned, and s1 and s2 are same
will not be printed. But the result is: both lines are printed. So that means, by default String constants are interned. But if it is so, then why do we need the intern
method? In other words when should we use this method?
When two strings are created independently,
intern()
allows you to compare them and also it helps you in creating a reference in the string pool if the reference didn't exist before.When you use
String s = new String(hi)
, java creates a new instance of the string, but when you useString s = "hi"
, java checks if there is an instance of word "hi" in the code or not and if it exists, it just returns the reference.Since comparing strings is based on reference,
intern()
helps in you creating a reference and allows you to compare the contents of the strings.When you use
intern()
in the code, it clears of the space used by the string referring to the same object and just returns the reference of the already existing same object in memory.But in case of p5 when you are using:
Only contents of p3 are copied and p5 is created newly. So it is not interned.
So the output will be: