Java字符串创建和字符串常量池

Ada*_*dam 12 java string string-literals

使用关键字new创建String时,它使用带有String文字的构造函数创建一个新的String对象.我想知道在调用String构造函数之前文字是否存储在常量池中.

我问的原因是,在"OCA Java SE 7程序员I认证指南"中,Mala Gupta写道:

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

她在第一行说,new创建的String对象没有存储在常量池中.这很好,但不清楚的是,如果第一行的构造函数中的文字"Summer"是.

在第二行,她说"Summer"的分配到summer2将它存储在常量池中,这意味着第一行的文字没有放在池中.

我的问题

  1. 第1行:在调用String构造函数之前,构造函数中的文字"Summer"是否放在常量池中?
  2. 第2行:第2 的池中是否已经存在"Summer",或者它是否插入此行?
  3. 第2行:当她说"夏天"插入第2行的游泳池时,作者是否错了?

Sur*_*tta 10

总之,没有混淆,

你写了 ,

   String summer  = new String("Summer");   //Line 1: The code creates a new String object with the value "Summer". This object is not placed in the String constant pool.
Run Code Online (Sandbox Code Playgroud)

那是错的.特别是评论>This object is not placed in the String constant pool.

字符串文字"Summer"现在在池中.并且summer在堆中创建对象.

在调用String构造函数之前,构造函数中的文字"Summer"是否放在常量池中?

是.它转到池,因为它是一个字符串文字.

"夏天"是否已经存在于第2行的池中,或者它是否插入此行?

不,因为你没有实习,所以有两个文字.(阅读更多关于字符串实习)

当她说"夏天"放在第2行的游泳池时,作者是错的吗?

其他是正确的那条线.

为了纪念,我们甚至可以简单地说,""无论它在何处使用,它们之间的所有内容都会进入池中.