【发布时间】:2014-07-16 11:27:11
【问题描述】:
当使用关键字 new 创建一个字符串时,它会使用一个接受字符串字面量的构造函数创建一个新的字符串对象。
在调用 String 构造函数之前,字面量是否存储在常量池中?
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 创建的 String 对象没有存储在常量池中。这很好,但不清楚的是第一行构造函数中的文字“Summer”是否是。 在第二行中,她说将“Summer”分配给 summer2 将其存储在常量池中,这意味着第一行的文字没有被保留。
【问题讨论】:
-
创建字符串文字的副本当然是浪费 CPU 和代码。我认为这只是出于教育目的。 ;)
-
长 comment 变短了。任何带有
""的东西都会进入字符串池。