【发布时间】:2020-01-09 05:50:09
【问题描述】:
根据 Java,
有两个地方存储字符串。字符串文字池和堆内存根据其创建。我需要知道,当一个字符串赋值给另一个字符串时,新创建的字符串会存储在哪里?
我已经对堆和字符串池中的字符串类型进行了赋值操作。我得到了这样的结果。
String str = new String("foo"); ===> str is created in heap memory
String strL = "doo"; ===> strL is created in String pool.
但是什么时候,
String strNew = strL; // strL which is there in String Pool is assigned to strNew.
现在,如果我这样做
strL = null;
System.out.println(strNew)// output : "doo".
System.out.println(strL)// output : null.
同样,
String strNewH = str; // str which is there in heap is assigned to strNewH
现在,
str = null;
System.out.println(strNewH);// output : "foo".
System.out.println(str); // null
以上是我在 IDE 上得到的输出。 根据此输出,在字符串池中创建了一个新的 strNew 引用对象,并在堆中创建了一个新的 strNewH 引用对象。对吗?
【问题讨论】:
-
字符串常量池是堆内存的一个区域...
-
感谢您的回复。但我需要知道 strNew 和 strNewH 到底在哪里?堆还是字符串池常量?
标签: java string object heap-memory string-pool