jdk 1.8
先拋結論
1.只在常量池上建立常量

2.只在堆上建立物件

3.在堆上建立物件,在常量池上建立常量

4.在堆上建立物件,在常量池上建立引用

注意:
-
常量池有兩種情況:引用(指標) 或 常量。如果該位置已經是引用或常量了,之後的操作都不會改變裡面的情況!!!
-
呼叫
intern()
(jdk1.8): 如果常量池裡是空的,就建立引用(指向堆,參考結論4);非空,不操作。返回值都是常量池裡的內容。 -
堆中可以有任意個相同的字串,常量池只能有一個(引用 或 常量)。
-
" " 和intern() 其實很像。區別就是在常量池為空時,“ ”是把值加進去,intern()是把引用加進去。
根據結論解決例子
例一
String s1 = new String("zxy"); // 結論3
s1.intern(); // 常量池非空,返回值是常量池裡的內容
String s2 = "zxy"; // 常量池非空,返回值是常量池裡的內容
System.out.println(s1 == s2); //false
System.out.println(s1.intern() == s2); // true
複製程式碼

例二
String s1 = "zxy"; // 加到常量池
String s2 = new String("zxy"); // 加到堆,常量池有東西所以啥也不幹
System.out.println(s1 == s2); // false
System.out.println(s1 == s2.intern()); // true 常量池非空,intern返回常量池裡的內容
複製程式碼
