Java 中的字符串池

Sheeraz Gul 2023年10月12日
Java 中的字符串池

字符串池是 Java 堆中的一个存储区域。它是 Java 虚拟机存储字符串的特殊内存区域。

本教程解释并演示了 Java 中的字符串池。

Java 中的字符串池

字符串池用于提高性能并减少内存开销。

字符串分配对时间和内存的成本很高,因此 JVM 在初始化字符串的同时执行一些操作以降低这两种成本。这些操作是使用字符串池执行的。

每当一个字符串被初始化时,Java 虚拟机都会首先检查池,如果初始化的字符串已经存在于池中,它会返回一个对池化实例的引用。如果初始化的字符串不在池中,则会在池中创建一个新的字符串对象。

下图演示了 Java 堆中字符串池的概览。

Java 中的字符串池

这是字符串池如何工作的分步过程;让我们以上面的图片为例。

当类被加载时,Java 虚拟机开始工作。

  1. JVM 现在将查找 Java 程序中的所有字符串文字。
  2. 首先,JVM 找到字符串变量 d1,它具有字面量 Delftstack1; JVM 将在 Java 堆内存中创建它。
  3. JVM 在字符串常量池内存中放置对文字 Delfstack1 的引用。
  4. JVM 然后寻找其他变量;如上图所示,它会找到带有文字 Delfstack2d2 和带有与 d1 相同文字的 d3,即 Delftstack1
  5. 现在,字符串 d1d3 具有相同的文字,因此 JVM 会将它们引用到字符串池中的同一对象,从而为另一个文字节省内存。

现在让我们运行 Java 程序,演示图中描述的示例和过程。参见示例:

package Delfstack;

public class String_Pool {
  public static void main(String[] args) {
    String d1 = "Delftstack1";
    String d2 = "Delftstack2";
    String d3 = "Delftstack1";

    if (d1 == d2) {
      System.out.println("Both Strings Refers to the same object in the String Pool");
    } else {
      System.out.println("Both Strings Refers to the different objects in the String Pool");
    }

    if (d1 == d3) {
      System.out.println("Both Strings Refers to the same object in the String Pool");
    } else {
      System.out.println("Both Strings Refers to the different objects in the String Pool");
    }
  }
}

此代码将与图片中的示例完全相同,并为三个变量创建两个对象。见输出:

Both Strings Refers to the different objects in the String Pool
Both Strings Refers to the same object in the String Pool
作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - Java String