根据 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 引用对象。这是对的吗?