Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
176 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...