Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison of "java" with intern() is false [duplicate]

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;
like image 267
linq lou Avatar asked Nov 24 '25 13:11

linq lou


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.

like image 113
Eran Avatar answered Nov 26 '25 02:11

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!