new String的值是存储在堆中还是常量池呢?

2021-03-14  本文已影响0人  单名一个冲

面试问:new String的值是存储在堆中还是常量池呢?

在Java中,我们知道new出来的对象会存储在堆中,那new String在JMM中是怎么存储的呢?

稍微有点基础的同学都知道,String x = "常量池"; 这段代码呢,Java会将字符串存储在常量池中。
但是String x = new String("常量池"); 这段代码,字符串存储在哪里呢?尤其这个就变成了面试同学的坑。

new String在JMM的存储位置.png
// 代码如下:
char[] f = {'a', 's', 'd'};

String a = "asd"; // 常量池
String b = new String("asd"); // 字符串形式new
String c = new String(f); // 数组形式new
String d = new String(f).intern(); // 数组形式new,使用intern方法
String b2 = new String("asd").intern(); // 字符串形式new

System.out.println(a + b + c + d); // 断点打在这里,只是为了防止jvm编译对代码优化

System.out.println(a == b); // false
System.out.println(a == b2); // true
System.out.println(a == d); // true
System.out.println(b == d); // false
System.out.println(c == d); // false

提出疑问:

带着疑问,我们来一步步解惑:

intern方法的作用:
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the #equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

意思是说:调用intern方法时,如果常量池中包含equals(Object)方法相同的字符串,则返回常量池中的字符串。 否则,将此String对象添加到常量池中,并返回对此String对象的引用。实则这个引用就是常量池中字符串;

所以,我们在对一个new出来的String的对象使用该方法时,它返回的是常量池中值。
这也就解释了为何 d(或b2)变量等于a变量,因为他俩都为常量池中同一个地址,但还不能证明new String是如何存放。

好,那么看看String类的几个构造函数吧:


String的一个构造.png

因为String类型是一个不可变类型,而以new String("字符串")这种方式创建字符串时,当你传入实参,实参其实已经在常量池创建了一个字符串original,等同于String original = "字符串";然后 this.value = original.value 是将常量池中字符串的char数组的引用指向了将要创建的对象的value属性,切记只是引用,而真正的值是在常量池中。
这也就是为何局部变量表指向同一个地址的原因,而引用呢则是放在了堆中的String对象中。

因为char数组是不会直接放入常量池的,所以在这个构造中:this.value = Arrays.copyOf(value, value.length);
是对实参变量做了拷贝,存储在堆中;如果对c变量做intern,则是把c的字符串值添加到常量池并返回。

注意编码规范:不要对动态char数组创建String字符串时添加intern方法,小心把你方法区干没,导致堆外内存溢出。这可能也是该构造的字符串不放常量池的原因吧。

总结:

  1. 对于直接声明的字符串,形如:String x = ""; 则变量x直接指向常量池中;
  2. 对于new出来的字符串,new String(""); 则存储于堆中,但存储的是指向常量池的引用;
  3. intern方法可以向常量池存储字符串,并返回一个常量池的引用对象;

实验环境:jdk1.8

上一篇 下一篇

猜你喜欢

热点阅读