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

AJJ*_*AJJ 3 java string equals string-concatenation

我试图通过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();
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

false
Object and literal compare by equals :: true
false
Literal compareing by equals :: true
Run Code Online (Sandbox Code Playgroud)

更新:答案

如果没有s1 == s2的括号,JVM将字符串比较为"对象和文字比较双等于:: jai"=="jai",结果为false.因此,不会打印sysout中的实际内容.当添加括号时,JVM将字符串比作"jai"=="jai",结果为

Object and literal compare by double equal to :: true

Chr*_*ian 7

当你这样做

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

你首先将字符串"Object and literal compare by double equal to :: "与字符串连接起来s1,这将给出

"Object and literal compare by double equal to :: jai"
Run Code Online (Sandbox Code Playgroud)

那么,你正在检查这个字符串是否是同一个对象(相同的引用),而不是s2:

"Object and literal compare by double equal to :: jai" == "jai"
Run Code Online (Sandbox Code Playgroud)

这将是false(输出将是false).

换句话说,这是因为运营商优先.在操作之前"操纵"操作符的一种方法是使用括号.括号内的操作将首先被解析:

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


lau*_*une 5

加括号!

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

PLus和其他算术运算比比较运算具有更高的优先级。对于concat使用'+'不会改变它。