问题
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
回答1:
+ 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.
回答2:
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.
回答3:
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 "
回答4:
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
回答5:
Comparing two String should always be done with the equals
method. otherwise you compare if it is the same reference, not the same value!
来源:https://stackoverflow.com/questions/33914808/string-concatenation-and-comparison-gives-unexpected-result-in-println-statement