public class Tst10 {
public static void main(String[] args)
{
String str="ABC";
if(str == "ABC"){
System.out.println("One");
}
if(str == new String("ABC")){
System.out.println("Two");
}
}
}
运行结果:
One
[b]==比较的是变量的值,而equals比较的是引用的内容。
[/b]
第7行:
str 和 "ABC" 都指向 字符串池中的“ABC”字符串,所以它们的值是相等的。
第10行:
new 操作导致产生新的对象,故该对象的引用比如与 字符串池中的“ABC”的引用不同。
所以,结果是输出One, 而没有输出Two。