常量池、棧、堆的關係圖如下
代碼說明
package com.taoshu.zhifu.workdemo.wk;
/**
* Created by yanyg on 2020-05-14.
*/
public class Test {
public static void main(String[] args) {
/**
* 1、從常量池中找,沒有,則在常量池中創建 hello 對象,然後使用,即棧中的引用變量 str1 指向常量池中的 hello 對象
* 2、從常量池中找,有的話,即直接使用,棧中的引用變量 str1 指向常量池中的 hello 對象
*/
String str1 = "hello";
String str2 = "hello";
System.out.println(str1==str2 );//true
/**
* 1、new 的話,會在堆中創建 hello 對象,而堆創建 hello 對象又會到常量池中去找,常量池中無,則在常量池中創建,然後堆中引用常量池中的 hello
* 1、new 的話,會在堆中創建 hello 對象,而堆創建 hello 對象又會到常量池中去找,常量池中有,則直接使用,即堆中引用常量池中的 hello
*/
String str3=new String("hello");
String str4=new String("hello");
String str5=new String("hello");
/**
* str3、str4 是引用變量,放在虛擬機棧的棧幀的局部變量表裏
* str3 指向堆中新創建的 hello
* str4 也指向堆中新創建的 hello
*/
System.out.println(str3==str4);//false
/**
* intern() 函數使 str5 也指向常量池中的 hello
*/
str5= str5.intern();
System.out.println(str1==str5);//true
}
}