【发布时间】:2023-04-06 09:02:02
【问题描述】:
我试图用字符串比较的输出来理解字符串连接。需要明确的是,我有一个类来使用 == 和 equals 比较两个字符串。我正在尝试将 == 和 equals() 的输出连接到一个字符串。 equals() 的输出连接,但 == 的输出不 连接。使用 java 的装箱功能,与字符串连接的布尔值将联系。据我所知,equals 和 == 返回布尔值。那么为什么会有这种差异呢?谁能解释一下?
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 equal to :: jai”== “jai”,结果为 false。所以 sysout 中的实际内容不会被打印出来。添加括号时,JVM 将字符串与 "jai" == "jai" 进行比较,结果为
Object and literal compare by double equal to :: true
【问题讨论】:
-
字符串被“吞下”不是很重要吗?
标签: java string equals string-concatenation