java – String equals和== with String concatenation
作者:互联网
参见英文答案 > Getting strange output when printing result of a string comparison 3个
我试图通过String compare的输出来理解String连接.为了清楚起见,我有一个类使用==和equals来比较两个字符串.我试图将==和equals()的输出连接到一个字符串. equals()concats的输出,但==的输出不会连续.使用java的装箱功能,与字符串连接的布尔值将联系.根据我的知识,equals和==都返回boolean.那为什么会有这种差异呢?任何人都可以解释一下吗?
public class StringHandler {
public void compareStrings() {
String s1 = new String("jai");
String s2 = "jai";
String s3 = "jai";
System.out.println("Object and literal compare by double equal to :: "
+ s1 == s2);
System.out.println("Object and literal compare by equals :: "
+ s1.equals(s2));
System.out
.println("Literal comparing by double equal to :: " + s2 == s3);
System.out.println("Literal comparing by equals :: " + s2.equals(s3));
}
public static void main(String[] args) {
StringHandler sHandler = new StringHandler();
sHandler.compareStrings();
}
}
产量
false
Object and literal compare by equals :: true
false
Literal compareing by equals :: true
更新:答案
如果没有s1 == s2的括号,JVM将字符串比较为“对象和文字比较双等于:: jai”==“jai”,结果为false.因此,不会打印sysout中的实际内容.当添加括号时,JVM将字符串比作“jai”==“jai”,结果为
对象和文字比较等于:: true
解决方法:
当你这样做
System.out.println("Object and literal compare by double equal to :: "
+ s1 == s2);
你首先将字符串“Object and literal compare by double equal to ::”与字符串s1连接起来,这将给出
"Object and literal compare by double equal to :: jai"
那么,你正在检查这个字符串是否是与s2相同的对象(相同的引用):
"Object and literal compare by double equal to :: jai" == "jai"
这将是假的(输出将是假的).
换句话说,这是因为操作符优先.在操作之前“操纵”操作符的一种方法是使用括号.括号内的操作将首先被解析:
System.out.println("Object and literal compare by double equal to :: " + (s1 == s2));
标签:java,string-concatenation,equals,string 来源: https://codeday.me/bug/20190712/1443734.html