常量池、栈、堆的关系图如下
代码说明
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
}
}