【问题标题】:Where will be the newly created String? Heap memory or String constant pool?新创建的字符串在哪里?堆内存还是字符串常量池?
【发布时间】: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


【解决方案1】:

你有一些误解。

字符串池也是堆的一部分。您可能想询问字符串是在字符串池中还是堆的其他部分

您似乎还认为分配会创建新对象。 他们没有。变量和对象是分开的东西。在这两行之后:

String str = new String("foo");
String strL = "doo";

变量str 引用一个字符串对象"foo",它不在字符串池中。变量strL引用一个字符串对象"doo",在字符串池中。

(注意“指”这个词)

当您分配String 变量时,您只是在更改它们所指的内容。这里:

String strNew = strL;

您正在使strNew 引用与strL 引用的对象相同的对象。

同样,当您将某些内容设置为 null 时,您将使其不引用任何内容。它所指的对象不一定被销毁。

至于你的问题:

根据此输出,strNew 的新引用对象在字符串池中创建,strNewH 的新引用对象在堆中创建。对吗?

不,这是不正确的。没有创建新对象。 strNew 指的是字符串池中的"doo",与strL 所指的对象是同一个对象。 strNewH 指的是"foo",它不在字符串池中,与str 所指的是同一个对象。

【讨论】:

  • 非常感谢@Sweeper。你的回答帮助我理解了字符串是如何工作的:)。
猜你喜欢
  • 2011-06-22
  • 2014-09-14
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 2012-12-18
相关资源
最近更新 更多