According to me == operators compares refrences .
That is correct. The ==
operator compares references if both operands are reference types. (It is not correct if either operand is a primitive type ... but that's a different topic.)
So b==c should print "true" But it prints "false" . I checked by printing hashcode of "b"and "c" .
Your reasoning is incorrect.
String a = "meow";
String b = a + "deal";
String c = "meowdeal";
In fact, when that code has finished b
and c
refer to different string objects that have the same value. In fact, the JLS states that the +
operator creates a new string objext ... unless the expression is a constant expression. (And it doesn't qualify as a constant expression in this case, because a
is a variable.)
So b == c
is false
... BECAUSE ==
is comparing references, and the references are different.