The difference between direct assignment of String and using new

String str2 = new String("ABC");

How many string objects are created by the above statement? The above statement actually creates two string objects, one is the object corresponding to the direct quantity "ABC", and the other is the string object returned by the new String() constructor.

In the JVM, considering the convenience of Garbage Collection, the heap is divided into three parts: young generation (new generation), tenured generation (old generation) (old generation), permanent generation (immortal generation) .

In order to solve the problem of string repetition, strings have a long life cycle and are stored in pergmen.

String str1 = "ABC"; may or may not create an object, if the string "ABC" does not exist in the java String pool, it will create a String object ("ABC") in the JVM's string pool, Then str1 points to this memory address. No matter how many string objects with the value "ABC" are created in this way, only one memory address is always allocated, and the next is a copy of String, which is called "string resident" in Java. linger", all string constants are automatically resident after compilation.

String str2 = new String("ABC"); creates at least one object, maybe two. Because the new keyword is used, a String object of str2 will definitely be created in the heap, and its value is "ABC". At the same time, if the string does not exist in the java String pool, the String object "ABC" will be created in the java pool.

public class Test2 {
    public static void main(String[] args) {
        String s1 = new String("ABC");
        String s2 = new String("ABC");
        System.out.println(s1 == s2);//false
        System.out.println(s1.equals(s2));//true
    }
}

如果将一个字符串连接表达式赋给字符串变量,如果这个字符串连接表达式的值可以在编译时就确定下来,那么JVM会在编译时确定字符串变量的值,并让它指向字符串池中对应的字符串。

But if the program uses variables or calls methods, the value of the string expression can only be determined at runtime, so the value cannot be determined at compile time, and the JVM's string pool cannot be used.

public class Test2 {
    public static void main(String[] args) {
        String s1 = "ABCDEF";
        String s2 = "ABC" + "DEF";
        System.out.println(s1 == s2); // true, 

        String s3 = "DEF" can be determined at compile time ;
        String s4 = "ABC" + s3;
        System.out.println(s1 == s4); // false, cannot be determined at compile time

        final String S5 = "DEF";
        String s6 = "ABC" + S5;
        System.out.println(s1 == s6); // true, use final keyword, macro substitution will be done on S5 at compile time 
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325089773&siteId=291194637