String concatenation and comparison gives unexpected result in println statement

旧巷老猫 提交于 2019-12-02 14:01:11
TheLostMind

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

The argument passed to println is evaluated left to right.

Therefore "str1==str2 "+ str1 concatenates two Strings, which are later compared to str2 and return a boolean.

It's because of operator precedence.

In the first statement the + operator is executed before the == and "str1==str2 " is appended to str1, after which the result of the appending is compared with == to str2.

In the second statement the brackets () denote the atomic pieces that should be evaluated before the top-level operators (i.e. the +) take place. This is why first str1 is compared to str2 with ==, and then the result (true) is appended as a String to the "str1==str2 "

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

in the above line, compiler checks if

"str1==str2"+str1

that is >>> "str1==str2 str1" is equal to str2 or not

That's why it prints it as false

Comparing two String should always be done with the equals method. otherwise you compare if it is the same reference, not the same value!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!