3

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;
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
linq lou
  • 71
  • 3
  • 1
    `java` is generally already interned by the JVM while `test` isn't. Hence the second call returns the object interned by the JVM not the one you created – Giacomo Alzetta Jun 05 '19 at 10:08
  • I can reproduce this if I run the two pairs of lines independently. Edited accordingly. – tobias_k Jun 05 '19 at 10:10
  • Its just two independent snippets, its irrelevant that the variable is declared again. – Zabuzard Jun 05 '19 at 10:15

1 Answers1

4

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.

Eran
  • 387,369
  • 54
  • 702
  • 768