String comparison of "java" with intern() is false

Viewed 98

Below is my code, I don't know why two results are different

This prints true

// Building "test"
String str2 = new StringBuilder("te").append("st").toString();
System.out.println(str2.intern() == str2); // true;

But this prints false

// Building "java"
String str2 = new StringBuilder("ja").append("va").toString();
System.out.println(str2.intern() == str2); // false;
1 Answers

The String "java" is interned somewhere else, in code that is executed prior to your code (possibly in some JDK class). Therefore str2.intern() returns the already interned instance of "java", which is not == str2.

On the other hand, the String "test" wasn't interned prior to your call, so your intern call added it to the String pool, which means str2.intern() returned str2 in that case.

Related