s = "sss";
s.intern() 返回的是字符串s在字符串常量池中的引用。
首先判断字符串常量池中是否有 “sss” 如果有则返回其引用地址
如果没有则创建一个然后返回 sss 的引用地址
public static void main(String[] args) {
String s = new String("1");
s.intern();
String s2 = "1";
System.out.println(s == s2); //false
String s3 = new String("1") + new String("1");
s3.intern();
String s4 = "11";
System.out.println(s3 == s4); //true
}
String s3 = new String(“1”) + new String(“1”); ——> s3 引用对象的内容是 “11”,但是常量池中并没有 “11”
s3.intern(); 将 “11” 加入到常量池中,并使用 s3 的引用作为后续字符串 "11"的引用地址。
添加堆中“11”对象的引用到字符串常量池
字面量和非字面量不同:
String s1 = new String(“1”);//字面量 “1”,会放到字符串常量池中
String s2 = new String(“1”) + new String(“1”);// "11"不会放进常量池
s2.intern() // 将"11"对象的引用添加到常量池中
字符串常量池:
- 存储引用
使用intern(),默认将字符串对象的引用加入常量池(String s2 = new String(“1”) + new String(“1”))
- 存储字面量
字面量 == “1”,也就是写出来的,都会放到常量池
Q:String s1 = new String(“1”) + new String(“1”);创建了多少对象?
A:四个,分别是字符串常量池中创建 “1”,两个new ,以及一个 new String(“11”)对象.