字符串等于和==字符串连接

时间:2014-06-20 05:07:19

标签: java string equals string-concatenation

我试图通过String compare的输出来理解String连接。为了清楚起见,我有一个类使用==和equals来比较两个字符串。我试图将==和equals()的输出连接到一个字符串。 equals()concats的输出,但== 的输出不 concat。使用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将字符串比较为“Object and literal compare by double等于:: jai”==“jai”,结果为 false 。因此,不会打印sysout中的实际内容。添加括号后,JVM将字符串比作“jai”==“jai”,结果为

Object and literal compare by double equal to :: true

4 个答案:

答案 0 :(得分:7)

当你这样做时

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"

将是false(输出将是false)。

换句话说,这是因为运算符优先级。在操作之前“操纵”操作符的一种方法是使用括号。括号内的操作将首先被解析:

System.out.println("Object and literal compare by double equal to :: " + (s1 == s2));

答案 1 :(得分:4)

<强>问题:

+ s2 == s3

+符号的优先级高于==,因此它会在执行append之前先执行(==),因此只会"false"

您需要放置括号,以便检查字符串比较的结果。

同样parenthesis的{​​{3}}高于+,它会在将字符串附加到字符串之前先对其进行比较。

<强>样品

 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 compareing by double equal to :: " + (s2 == s3));
    System.out.println("Literal compareing by equals :: " + (s2.equals(s3)));

运算符优先级:

enter image description here

答案 2 :(得分:4)

添加括号!

  System.out.println("Object and literal compare by double equal to :: " +
                     (s1 == s2));

PLus和其他算术运算具有比比较运算更高的优先级。使用'+'进行连接不会改变它。

答案 3 :(得分:2)

这是一个操作顺序问题。它被解释如下(括号添加):

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 compareing by double equal to :: " + s2)  == s3);
System.out.println("Literal compareing by equals :: " + (s2.equals(s3)) );