Java hasn't operator overloading, like C++ and C# have. So, this means that the ==
operator always compares references. And the strings you are comparing might be the same, but they have a different reference. What causes false
.
But why was there a true result? Well, Java creates a String Pool. All String literals will be put in the String Pool at compile time. This means that:
String literalString1 = "foo";
String literalString2 = "foo";
literalString1 == literalString2 // true
Because it are both references to the String Pool.
But as soon as you start building strings (using +
), it will create new Strings on the heap. However, the Java compiler was smart and builded the two String literals at compile time.
"wel"+"come" == "welcome"
Because of you are building them at runtime. The compiler will detect "wel" + "come"
is a String literal and will put it in the String pool. And "welcome"
is a literal as well, and will search the String pool to check if the literal is already in the String Pool. And of course it will find it and use the same reference.