public class Test {
public static void main(String[] args) {
/**
* 理解是这样的:
* 1处代码的"1"在编译期间就已经放入常量池了,然后类加载后放入了运行时常量池(生成一个"1"的对象,将其引用放入) 然后生成一个"1"的字符串对象由s指向(这个对象并不在常量池中)
* 2处代码查看s这个对象的字符串内容"1"已经在字符串常量池了,就不将s的引用放入常量池了
* 3处代码s2引用的是常量池中的引用 所以最后结果是false
*
* 4处代码将"hel" 和"lo"分别创造对象,并保存其引用到常量池,然后生成一个新的String对象 s3内容为"hello"
* 5处代码发现s3的内容hello没有在常量池中,就将s3引用放入常量池
* 6处代码等于直接引用的s3 所以最后结果是true
* */
String s = new String("1"); // 1
s.intern(); // 2
String s2 = "1"; // 3
// false
System.out.println(s == s2);
String s3 = new String("hel") + new String("lo"); // 4
s3.intern(); // 5
String s4 = "hello"; // 6
// true
System.out.println(s3 == s4);
}
}
Java 中new String(“字面量“)
最新推荐文章于 2023-03-15 19:35:08 发布