为什么在Java中字符串字面量存储在字符串常量池中?

WBOY
WBOY 转载
2023-09-11 21:17:02 326浏览

为什么在Java中字符串字面量存储在字符串常量池中?

在 Java 中创建 String 对象有两种方法

  • 使用 new 运算符
String str = new String("Tutorials Point");
  • 通过使用字符串文字
String str = "Tutorials Point";

每当我们在Java中调用new String()时,它都会在堆内存中创建一个对象,并且字符串文字将进入字符串常量池(SCP)。

对于对象,JVM 使用 SCP,这是为了在 Java 中进行高效的内存管理。与其他Java对象不同,他们没有在堆区管理String对象,而是引入了String常量池。 String常量池的一个重要特性是,如果池中已有String常量,则不会创建相同的String对象。

示例

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

以上就是为什么在Java中字符串字面量存储在字符串常量池中?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除