為什麼在 Java 中將字串字面量儲存在字串常量池中?


在 Java 中有兩種建立 String 物件的方法

  • 透過使用 new 運算子

String str = new String("Tutorials Point");
  • 透過使用字串字面量

String str = "Tutorials Point";

每當我們在 Java 中呼叫 new String() 時,它都會在堆記憶體中建立一個物件,而字串字面量會進入字串常量池 (SCP)。

對於物件,JVM 使用 SCP,後者用於 Java 中的有效記憶體管理。與其他 Java 物件不同,他們引入了字串常量池而不是在堆區上管理字串物件。字串常量池的一個重要特性是,如果池中已有字串常量,它就不會建立相同的字串物件。

範例

public class SCPDemo {
   public static void main (String args[]) {
      String s1 = "Tutorials Point";
      String s2 = "Tutorials Point";
      System.out.println("s1 and s2 are string literals:");
      System.out.println(s1 == s2);
      String s3 = new String("Tutorials Point");
      String s4 = new String("Tutorials Point");
      System.out.println("s3 and s4 with new operator:");
      System.out.println(s3 == s4);
   }
}

輸出

s1 and s2 are string literals:
true
s3 and s4 with new operator:
false

更新日期:2023 年 11 月 17 日

2K+ 次瀏覽

開啟您的

透過完成課程獲得認證

開始
廣告
© . All rights reserved.