Below code return boolean false value. Any explanation for this ?
String str = "Bee";
String str2 = "Bee";
System.out.println("==" + str == str2);
Actual Result : false
Below code return boolean false value. Any explanation for this ?
String str = "Bee";
String str2 = "Bee";
System.out.println("==" + str == str2);
Actual Result : false
str
and str2
are both assigned the same String
instance, since String
literals are automatically stored in the String
pool. Therefore str == str2
is true
.
However, you are printing the expression "==" + str == str2
. That expression is evaluated from left to right, so first "==" + str
is evaluated, and results with the String
"==Bee". Then the ==
operator is applied to "==Bee" and "Bee", which returns false
.
If you change the statement to:
System.out.println("==" + (str == str2));
you'll get true
, since now the comparison will take place prior to the String
concatenation.
Use equals
to compare string, it will return true
for this case.
The ==
operator compares that the Strings are exactly the same Object
.
This might theoretically happen in case of internalized strings, but you cannot rely on this. For your case, comparing String
values, use str.equals(str2)
.