Search code examples
javastringoperator-precedence

String concatenation and comparison gives unexpected result in println statement


I couldn't figure out the following behaviour,

String str1= "abc";
String str2 = "abc";

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

Output for the above statement is as follows:

false

str1==str2 true

Why is this happening? Why the output is not like follows:

str1==str2 true

str1==str2 true


Solution

  • + has higher precedence than ==.
    So your code :

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

    will effectively be

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

    so, you get false.

    In case-2

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

    you have used braces explicitly to compare str1 with str2 (which is true) and then append the value.