The difference between String direct assignment and new String()

Direct assignment

It may or may not create an object. If the string "aaa" does not exist in the java String pool, a String object ("aaa") will be created in the java String pool.

Then str1 points to this memory address. No matter how many string objects with the value "aaa" are created in this way, only one memory address is always allocated, and the rest are copies of String.

Called "string resident" in Java, all string constants will automatically reside after compilation.

new String()

Create at least one object, or two. Because the new keyword is used, a String object of str11 will be created in the heap, and its value is "aaa".

At the same time, if the string does not exist in the java String pool, the String object "aaa" will be created in the java pool.

Test code:

public static void main(String[] args) {
    
          
        String str1 = "aaa";
        String str2 = "aaa";
        System.out.println(str1 == str2);

        String str11 = new String("aaa");
        String str22 = new String("aaa");
        System.out.println(str11 == str22);
}

result:

true
false

Guess you like

Origin blog.csdn.net/weixin_44371237/article/details/114665782