What is the difference between the string object created by the constructor and the string object created by the direct assignment method?

Code

Note: When the constant pool in the method area has the string, it will be used later, that is, to call the string in the method area (in fact), the string object created by the construction method and the string object created by the direct assignment method are essentially The above is the difference in calling method (so the address value is different)

package MyString;
/*
       构造方法创造的字符串对象和直接赋值方式创建的字符串对象有什么区别?
            猜想:存放字符串的地址值不同,方便程度不同

         结果:构造方法创建的字符串对象是在堆内存
              直接赋值方式创建的对象是在方法区的常量池。

             字符串的内容是存储在方法区的常量池内的,为了方便字符串的重复利用

       扩充:  == 比较符号两边的数值
                 基本数据类型:比较的是基本数据类型的值是否相同(true/false)
                 引用数据类型:比较的是引用数据类型的地址值是否相同(true/false)
 */
public class StringDemo2 {
    
    
    public static void main(String[] args) {
    
    
        String s5="hello";
        //构造方法创造的字符串对象
        String s1=new String("hello");
        //直接赋值方式创建的字符串对象
        String s2="hello";
        //先看输出值
        System.out.println("s1:"+s1);
        System.out.println("s2:"+s2);

        String s3="hello";
        String s4=new String("hello");
        System.out.println("s1==s2? "+(s1==s2));//false
        System.out.println("s1==s3? "+(s1==s4));//false
        System.out.println("s2==s4? "+(s2==s3));//true
        System.out.println("s5==s1? "+(s5==s1));//false
        System.out.println("s5==s2? "+(s5==s2));//true
        System.out.println("s5==s3? "+(s5==s3));//true
        //其中如果构造方法创建的字符串对象在直接赋值后,则直接赋值会在常量池开辟一个新内存存放该字符串
        //往后再有直接赋值与该字符串相同的数据,则栈内存方法直接指向该方法区的常量池内的该字符串地址
        //而构造方法由于在堆内存开辟了新的空间,所以需要二次(多次)寻址才能调用该常量池内的字符串
        //由此来看,除去第一次开辟后,常量池内有该字符串,字符串的利用还是直接赋值创建对象更加方便省事
    }
}

Icon

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_52646273/article/details/114128594