I know that String.intern() adds string to pool if it does not contain the object, but how to explain the results.
The code below:
public static void main(String[] args) {
char[] abc = new char[]{'a','b','c'};
String str = new String(abc);
System.out.println(str == "abc");
str.intern();
System.out.println(str == "abc");
}
output is :
false
false
However when code as below:
public static void main(String[] args) {
char[] abc = new char[]{'a','b','c'};
String str = new String(abc);
str.intern();
System.out.println(str == "abc");
}
The output is:
true
What's the difference.
The difference is that when you use the
Stringliteral "abc" before the explicit call tointern, it is implicitly interned.str.intern()doesn't store the instance referenced bystrin the String pool if an equalStringis already in the pool.First snippet:
Second snippet:
From the Javadoc of intern: