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

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...