程序将打印Equal
。(至少使用Sun Hotspot和suns
Javac。)此处在http://ideone.com/8UrRrk上进行了演示。
这是因为该字符串字面常量存储在一个事实 串池 和字符串的引用 可以 被重复使用。
进一步阅读:
- 什么是字符串文字池?
- 字符串实习
但是:
public class Salmon { public static void main(String[] args) { String str1 = "Str1"; String str2 = new String("Str1"); if (str1 == str2) { System.out.println("Equal"); } else { System.out.println("Not equal"); } }}Not equal由于
new可以保证会引入新的参考,因此将进行打印。
因此,经验法则: 始终使用该equals
方法比较字符串。



