字符串连接和比较在println语句中给出了意外的结果 [英] String concatenation and comparison gives unexpected result in println statement

查看:66
本文介绍了字符串连接和比较在println语句中给出了意外的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚以下行为,

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

上述声明的输出如下:


false

false

str1 == str2 true

str1==str2 true

为什么会发生这种情况?为什么输出不是如下:

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


str1 == str2 true

str1==str2 true

str1 == str2 true

str1==str2 true


推荐答案

+ 的优先级高于 ==

所以你的代码:

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

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

实际上是

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

所以,你得到 false

案例-2

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

您明确使用大括号来比较 str1 使用 str2 true )然后附加值。

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

这篇关于字符串连接和比较在println语句中给出了意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆