为什么在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP