0
public class Main {
    public static void main(String[] args) {
        String str1 = new String("Haseeb"); 
        String str2 = new String("Haseeb");
        System.out.println("str1==str2" + str1==str2  );
    }
}
  • output is "false"
  • I am expecting "str1==str2 false"
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

12

The == operator is of lower precedence than +, so + gets execute first.

"str1==str2" + str1 yields "str1==str2Haseeb".

Then == executes, and "str1==str2Haseeb" is not the same object as "Haseeb" (str2), so false is printed.

You can add parentheses to clarify the desired order of operations.

System.out.println("str1==str2 " + (str1==str2)  );

This should print str1==str2 false.

rgettman
  • 176,041
  • 30
  • 275
  • 357
4

(a + b == c) evaluates as (a + b) == c, not a + (b==c), because + has higher precedence than ==. Otherwise arithmetic wouldn't work.

What you have there is equivalent to:

System.out.println( ("str1==str2" + str1) ==str2  );

And ("str1==str2" + str1) is not equal to str2, so you print false.

What you probably mean is:

System.out.println("str1==str2 " + (str1==str2));
khelwood
  • 55,782
  • 14
  • 81
  • 108