java: String class

definition

String s1 = new String("aaa");
String s2 = "bbb";

Constant pool

Location:
jdk1.6: constant pool in the permanent generation in the method area
jdk1.7: constant pool in the heap memory
jdk1.8: constant pool in the meta space, independent of the heap

The aaa in the constant pool cannot be recycled:
Insert picture description here
Why is the constant in the constant pool not recycled: For
example, if you define a new one str3 = "bbb", you find that the constant pool already has a bbb, so a new space will not be created

problem

String s1 = new String("aaa");
String s2 = "aaa";
s1 === s2; // false
String s1 = "aaa";
String s2 = "aa";
String s3 = "a";
String s23 = s2 + s3; // s23不是字符常量,不是使用双引号直接创建的字符串
s1 === s23; // false
String s1 = "aaa";
String s23 = "aa" + "a"; // s23是字符常量,对于常量与常量的运算,在编译期已经得到了值。
s1 === s23; // true

Guess you like

Origin blog.csdn.net/weixin_43972437/article/details/113869337