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()
.