"Hello" == "Hello"
is true, despite the fact that String
is a reference type. This optimization is possible thanks to the immutability of the String String
class, and is known as string interning.Besides literals themselves, interning is applied to all constant expressions. In this example, the implicit conversion of the number
42
to a string and the concatenation of constants are considered constant expressions. This makes "Hello_42" == "Hello_" + 42
true.The literal pool does not work when the
new
operator is explicitly used. This is why the entire expression new String("Hello_42") == "Hello_" + 42
is false.