【发布时间】:2013-05-22 04:32:10
【问题描述】:
public static void main(String[] args){
one();
two();
three();
}
public static void one() {
String s1 = "hill5";
String s2 = "hill" + 5;
System.out.println(s1==s2);
}
public static void two() {
String s1 = "hill5";
int i =5;
String s2 = "hill" + i;
System.out.println(s1==s2);
}
public static void three() {
String s1 = "hill5";
String s2 = "hill" + s1.length();
System.out.println(s1==s2);
}
输出是
true
false
false
字符串文字使用实习过程,那么为什么two()和three()是假的。我可以理解three()但two()不清楚。但需要对这两种情况进行适当的解释。
有人可以解释一下正确的理由吗?
【问题讨论】:
-
阅读我问过的这个问题stackoverflow.com/questions/16729045/…
-
为了好玩,你也可以试试
two和final int i = 5;代替(它会打印true而不是false,因为现在i是一个常量)。 -
“每当有人将字符串与 == 开发人员进行比较时...”
-
请注意,您永远不应该依赖
==来比较字符串——它会使您的程序变得脆弱。这只是一个字符串何时被保留的问题,这取决于使用的编译器(在one()中)和使用的 JVM。 -
是的,我只想知道概念。
标签: java string string-concatenation