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

我试图理解字符串连接与String比较的输出。 为了清楚起见,我有一个类使用==和equals来比较两个字符串。 我试图将==和equals()的输出连接到一个字符串。 equals()concats的输出,但==的输出不会连接。 使用java的装箱function,与字符串连接的布尔值将联系。 根据我的知识,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

当你这样做

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

添加括号!

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

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

问题:

 + s2 == s3 

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

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

parenthesis 优先级高于+符号,它会在将字符串附加到字符串之前先对其进行比较。

样品

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

运算符优先级:

在此处输入图像描述

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

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