java 面試題: new String() 會創建幾個對象?

題1: String str =new String(“ab”) 會創建幾個對象?

public class StringNewTest {
    public static void main(String[] args) {
        String str = new String("ab");
    }
}

javap -v StringNewTest.class 反編譯後, 部分片段如下:

在這裏插入圖片描述

根據反編譯後字節碼分析:

  1. 一個對象是:new關鍵字在堆空間創建的;
  2. 另一個對象是:字符串常量池中的對象"ab"。 (如果前後文中還有代碼,並且已經有 ab 常量在常量池存在時,ab 將不再創建,因爲在常量池只能存在一份相同的對象)

結論是至少是2個對象。

題2:String str =new String(“a”) + new String(“b”) 會創建幾個對象 ?

public class StringNewTest {
    public static void main(String[] args) {
        String str = new String("a") + new String("b");
    }
}

javap -v StringNewTest.class 反編譯後, 部分片段如下:
在這裏插入圖片描述

根據反編譯後字節碼分析:

對象1: new StringBuilder()
對象2: new String(“a”)
對象3: 常量池中的"a"
對象4: new String(“b”)
對象5: 常量池中的"b"

深入剖析: StringBuilder 的 toString() 方法中有 new String(value, 0, count)
對象6 :new String(“ab”)

強調一下:
StringBuilder 的 toString() 的調用,在字符串常量池中,沒有生成"ab"。
如果前後文中還有代碼,並且已經常量在常量池存在時,相同的常量 將不再創建,因爲在常量池只能存在一份相同的對象。

結論是至少是6個對象。

題3:String str =“a”+ “b” 會創建幾個對象 ?

public class StringNewTest {
    public static void main(String[] args) {
        String str = "a" + "b";
    }
}

javap -v StringNewTest.class 反編譯後, 部分片段如下:
在這裏插入圖片描述
"a" + "b" 在編譯時,就已經編譯爲 ab, 被放到常量池中。
所以只有一個對象 :ab

注意:
如果前後文中還有代碼,並且已經有 ab 常量在常量池存在時,ab 將不再創建,因爲在常量池只能存在一份相同的對象。

字符串拼接操作的總結

  • 常量常量 的拼接結果在 常量池,原理是 編譯期 優化;
  • 常量池 中不會存在相同內容的常量;
  • 只要其中一個是變量,結果在堆中。 如: String s2 = s1+"DEF" ;
    變量拼接的原理 是StringBuilder 。
  • 如果拼接的結果是調用 intern() 方法,則主動將常量池中 還沒有的字符串 對象放入池中,並返回地址。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章