[英]Java String creation and String constant pool
使用關鍵字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.
}
她在第一行說, new創建的String對象沒有存儲在常量池中。 這很好,但不清楚的是,如果第一行的構造函數中的文字“Summer”是。
在第二行,她說,將Summer“”分配給summer2將它存儲在常量池中,這意味着第一行的文字不會放在池中。
我的問題
總之,沒有混淆,
你寫了 ,
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.
那是錯的。 特別是注釋> This object is not placed in the String constant pool.
字符串文字“Summer”現在在池中。 而對象summer
在堆中創建。
在調用String構造函數之前,構造函數中的文字“Summer”是否放在常量池中?
是。 它轉到池,因為它是一個字符串文字。
“夏天”是否已經存在於第2行的池中,或者它是否插入此行?
不,因為你沒有實習,所以有兩個文字。 (閱讀更多關於字符串實習 )
當她說“夏天”放在第2行的游泳池時,作者是錯的嗎?
其他是正確的那條線。
為了紀念,我們甚至可以簡單地說""
之間的所有內容都會進入池中,無論它在何處使用。
代碼1 - 第1行:在調用String構造函數之前,構造函數中的文字“Summer”是否放在常量池中?
是。 JLS聲明:
這是因為字符串文字 - 或者更常見的是作為常量表達式(第15.28節)的值的字符串 - 被“實例化”以便使用String.intern方法共享唯一實例。
由於該字符串是文字(因此是常量表達式的值),因此將插入該字符串。 但是,分配給變量summer
的對象不是相同的文字,它顯式是一個新的字符串對象,用於復制該文字的值。
代碼1 - 第2行:第2行的池中是否已經存在“Summer”,或者它是否插入此行?
如上所述,它已經插入。
代碼2 - 第2行:當她說“夏天”放在第2行的游泳池時,作者是否錯了?
不 - 雖然我同意措辭可能更清楚。
**Code 1 - Line 1: Does the literal "Hello" in the constructor get placed in the constant pool before the String constructor is called?**
是的 ,因為構造函數用於實例化對象。
****Code 1 - Line 2: Does "Hello" already exist in the pool at line 2 or is it inserted at this line?****
**它已經存在了**。 它沒有插入此行。 你可以這樣檢查。
String s=new String("hello");
String s1=s.intern();
String s2 = new String("hello");
String s3= s2.intern();
if (s1==s3)
{
System.out.println("true");
} if (s==s2)
{System.out.println("false");}
代碼2 - 第2行:當她說“夏天”放在第2行的游泳池時,作者是否錯了?
不 。 夏天不會被放置在恆定的游泳池,因為它已經存在,code2-line1將在那里放置“夏天”。
public static void main(String[] args)
{
String summer = new String("Summer"); //Line 1: The code creates a new String object
}
值得Summer
。 此對象未放置在String常量池中。
這種說法是錯誤的。 ABove行將創建2個對象,一個位於常量池中,另一個位於堆中。無論何時編寫“ABC”,無論內部構造函數如何,它都將進入常量池。
證明
String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();
String s4 = new String("Rakesh");
String s5 = new String("Rakesh").intern();
if ( s1 == s2 ){
System.out.println("s1 and s2 are same"); // 1.
}
if ( s1 == s3 ){
System.out.println("s1 and s3 are same" ); // 2.
}
if ( s1 == s4 ){
System.out.println("s1 and s4 are same" ); // 3.
}
if ( s1 == s5 ){
System.out.println("s1 and s5 are same" ); // 4.
}will return:
s1 and s2 are same
s1 and s3 are same
s1 and s5 are same
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.