-4

Below code return boolean false value. Any explanation for this ?

String str = "Bee";
String str2 = "Bee";
System.out.println("==" + str == str2); 

Actual Result : false

  • 1
    Yes, that's strange. I also don't see why "==Bee" and "Bee" aren't the same String. – Tom Jun 13 '19 at 13:55
  • A good place to start here : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – TechFree Jun 13 '19 at 14:37

2 Answers2

0

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

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).

Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34