【发布时间】:2021-04-18 17:36:11
【问题描述】:
我知道如果我有 2 个具有相同值的字符串变量,由于 java 字符串池,它们指向同一个字符串对象。
这是一个例子:
String test = "1234";
String test2 = "1234";
System.out.println(test == test2);
System.out.println("1234" == test2);
输出如下:
true
true
但如果我有以下代码,它会打印出它们不是同一个对象
String test = "1234";
int i = 1234;
String s = "" + i;
System.out.println(test == s);
System.out.println("1234" == s);
输出:
false
false
请谁给我解释一下这种行为的原因?
【问题讨论】:
-
I know that if I have 2 string variables with the same value, they point to the same string object because of the java string pool.不,他们没有。 -
这是因为
i根据 Java 对该术语的非常狭隘的定义,它不是一个常量表达式。 -
字符串池用于字符串常量。
"" + i不是字符串常量。参考stackoverflow.com/questions/2486191/… -
这能回答你的问题吗? How do I compare strings in Java?
-
@Sachin - 您提出的重复目标没有回答这个问题。