字符串等于和==字符串连接 [英] String equals and == with String concatenation
问题描述
我试图通过String compare的输出来理解String连接。为了清楚起见,我有一个类使用==和equals来比较两个字符串。我试图将==和equals()的输出连接到一个字符串。 equals()concats的输出,但== 的输出不 concat。使用java的装箱功能,与字符串连接的布尔值将联系。根据我的知识,equals和==都返回boolean。那为什么会有这种差异呢?任何人都可以解释这个吗?
I am trying to understand the String concatenation with the output of String compare. To be clear, i have the class to compare two strings using == and equals. I am trying to concat the output of == and equals() to a string. The output of equals() concats, but the output of == does not concat. Using boxing feature of java, the boolean concatenated with string will contact. Both equals and == returns boolean to my knowledge. So why is this difference? Can anyone explain on this?
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将字符串比较为Object and literal compare by double等于:: jai==jai,结果为 false 。因此,不打印sysout中的实际内容。当添加括号时,JVM将字符串比较为jai==jai,结果为
Without parenthesis for s1==s2, the JVM compares the string as "Object and literal compare by double equal to :: jai" == "jai" and the result is false. So the actual content in sysout is not printed. When parenthesis is added the JVM compares the string as "jai" == "jai" and the result is
对象和文字比较双倍等于to :: true
推荐答案
当你这样做时
System.out.println("Object and literal compare by double equal to :: "
+ s1 == s2);
你是第一个连接字符串对象和文字比较双倍等于::
,字符串为 s1
,这将给出
you are first concatenating the string "Object and literal compare by double equal to :: "
with the string s1
, which will give
"Object and literal compare by double equal to :: jai"
然后,你正在检查此字符串是否与 s2
相同的对象(相同的引用):
then, you are checking if this string is the same object (same reference) than s2
:
"Object and literal compare by double equal to :: jai" == "jai"
这将是 false
(输出将是 false
)。
换句话说,这是因为运算符优先级。在操作之前操纵操作符的一种方法是使用括号。括号内的操作将首先被解析:
In other words, it's because operators precedence. One way to "manipulate" operators precedende is to use parentheses. The operations inside parentheses will be parsed first:
System.out.println("Object and literal compare by double equal to :: " + (s1 == s2));
这篇关于字符串等于和==字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!