java-String类-String s = new String(“hello”)和String s = “hello”;的区别

**

1.String s=new String(“hello”);的创建过程:

**
在这里插入图片描述
**

2.String s=new String(“hello”);的创建过程**

在这里插入图片描述
**

3.代码测试**

        String s1 = "hello";
        String s2 = "hello";
        System.out.println(s1 == s2);   //true
        System.out.println(s1.equals(s2));//true

        String s3="hello";
        String s4=new String("hello");
        String s41=new String("hello");
        System.out.println(s3==s4); //false
        System.out.println(s3.equals(s4));  //true
        System.out.println(s4==s41);//false

        String s5="hello";
        String s6="h"+"ello";
        String s7="h";
        String s8="ello";
        String s9=s7+s8;
        System.out.println(s5==s6);//true
        System.out.println(s5==s9);//false

        String s10=new String("hello");
        String s11="h"+new String("ello");
        String s12=new String("h")+new String("ello");
        String s13="hello";
        System.out.println(s10.intern()==s13);//true
        System.out.println(s11.intern()==s13);//true
        System.out.println(s12.intern()==s13);//true

总结:
1.使用直接赋值的方式,直接在常量池中进行寻找,找到了就直接把把这个地址值赋值给变量,否则先在常量池中创建,然后把地址值再进行赋值。
2.new String(“hello”);需要创建两个对象,new关键字创建时,前面的操作和字面量创建一样,只不过最后在运行时会创建一个新对象,变量所引用的都是这个新对象的地址。
3.equals()方法本来比较的两个对象的地址值,但是String类重写了父类的方法,用来去比较两个字符串字符串字面上的内容是否相同

发布了46 篇原创文章 · 获赞 1 · 访问量 1017

猜你喜欢

转载自blog.csdn.net/qq_42022411/article/details/102648490