Boring to rely on JavaEE from entry to abandon (11) string class _ constant pool principle

One. String class and constant pool

1. String basics

String numbers are called immutable character sequences.
String is located in the java.lang package, and the Java program imports all classes in the java.lang package by default.
A Java string is a sequence of Unicode characters. For example, the string "Java" is composed of 4 Unicode characters'J','a','v', and'a'.
Java does not have a built-in string type, but provides a predefined class in the standard Java class library:
String, each string enclosed in double quotes is an instance of the String class.

 

The toString() method is to print: class name@object address, but the string is output as it is when printing the string, because the String class rewrites the toString() method.

Sample code:

public class string {
    public static void main(String[] args) {
        String str1="abc";
        String str2=new String("abc");

        System.out.println(str1==str2);
        System.out.println(str1);//会自动调用toString()函数,但是String类重写了
        System.out.println(str2);
        System.out.println(str1.equals(str2));//比较字符串内容时用此函数
    }
}

Output:

false
abc
abc
true

The reason why str1==str2 returns false is as follows:

It can be seen that the address of str1 is 0x1, and the address of str2 is 0x2, str1==str2 compares the object address again, and obviously returns false

2. Constant pool

In the memory analysis of Java, we will often hear about the description of "constant pool", in fact, the constant pool is also divided into the following three:
1. Global string constant pool (String Pool)
stored in the global string constant pool The content is stored in the String Pool after the class is loaded, there is only one copy in each VM, and the reference value of the string constant is stored (the string object instance is generated in the heap).
2. Class Constant Pool The
class constant pool is owned by every class during compilation. In the compilation phase, constants (text strings, final constants, etc.) and symbol references are stored.
3. Runtime Constant Pool (Runtime Constant Pool)
After the class is loaded, the symbol reference value in each class constant pool is dumped into the runtime constant pool.

In other words, each class has a runtime constant pool. After the class is parsed, the symbol reference is replaced with a direct reference, which is consistent with the reference value in the global constant pool.

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_44593822/article/details/115381943