String str 与 String str=new String("") 区别

1.当使用String str="abc",这种方式时,先去内存的Heap中找是否存在"abc"这个字符串,若存在,则将地址引用。若不存在则创建。

2.当使用String str=new String("abc");时,不管事先是否存在"abc",每次都会创建其新的对象。

测试一下:

        String s1="abc";  
        String s2="abc"; 
        String s3=new String("abc");    

        String s4=new String("abc");


        System.out.println(s1 == s2);  
        System.out.println(s2 == s3);  

        System.out.println(s1 == s3);

        System.out.println(s4 == s3);

打印的结果为:

        true
        false
        false

        false

为什么呢?

参看以上两点可知,s1,s2引用的是相同的地址,故为true

                           s3又创建了一个新的"abc"对象,故为false

原文地址:https://www.cnblogs.com/0515offer/p/4181860.html