有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java字符串创建和字符串池

当使用关键字new创建字符串时,它使用接受字符串文本的构造函数创建一个新的字符串对象

在调用字符串构造函数之前,文本是否存储在常量池中

String hello = new String("Hello");
String literal = "Hello";             //Does "Hello" already exist in the pool
                                      //or is it inserted at this line?

编辑

在“OCA Java SE 7程序员I认证指南”中,Mala Gupta写道:

public static void main(String[] args)
{
    String summer  = new String("Summer");   // The code creates a new String object with the value "Summer". This object is not placed in the String constant pool.
    String summer2 = "Summer"                // The code creates a new String object with the value "Summer" and places it in the String constant pool.
}

她在第一行说,由new创建的字符串对象没有存储在常量池中。这很好,但不清楚的是,第一行构造函数中的文字“Summer”是否正确。 在第二行中,她说将“Summer”赋值给summer2将其存储在常量池中,这意味着第一行中的文字不是interned


共 (3) 个答案

  1. # 1 楼答案

    无论在何处使用,所有字符串文字都保存在字符串池中。所以答案是肯定的

    String hello = new String("Hello");
                            >    <  goes to pool.
    

    但问题是h2不会引用该h:)

  2. # 2 楼答案

    在代码中写入"Hello"时,将在编译期间创建此字符串。 实际上它已经存在了,因为您还使用它来创建new String("Hello"); 里面有"Hello"。 总之:是的

  3. # 3 楼答案

    String ob1 = new String("Hello");
    String ob2 = "Hello"; 
    

    第一行首先在字符串池中寻找一个"Hello" string,若它在那个里,它在堆中创建相同的对象,我们的ob1引用那个堆对象。若它不在那个里,它也会在池中创建相同的对象,在本例中,ob1也引用heap对象。 第二行还查找池中的"Hello" object,如果找到的ob2将引用该池对象。如果找不到,它将仅在池中创建,ob2将引用该池对象。 但第二行从不在堆中创建字符串对象。保留在字符串池中的字符串对象是可重用的,但在堆中创建的字符串对象不是