java string字符拼接符"+"的研究

程序:

 
public class Test {
    public static void main(String args[]) {
        String s1 = "abc";
        String s2 = "abc";
        String s3 = "abc" + "def";
        String s4 = "abcdef";
        String s5 = s2 + "def";
        String s6 = new String("abc");
        System.out.println(s1 == s2);
        System.out.println(s3 == s4);
        System.out.println(s4 == s5);
        System.out.println(s4.equals(s5));
        System.out.println(s6.equals(s1));
        System.out.println();
        System.out.print(
                "\ns1:"+System.identityHashCode(s1)+
                "\ns2:"+System.identityHashCode(s2)+
                "\ns3:"+System.identityHashCode(s3)+
                "\ns4:"+System.identityHashCode(s4)+
                "\ns5:"+System.identityHashCode(s5)+
                "\ns6:"+System.identityHashCode(s6));

    }
    }

 内存模型图:

结果:

true
true
false
true
true

s1:557041912
s2:557041912
s3:1134712904
s4:1134712904
s5:985922955
s6:1435804085
由结果可知

         s1和s2指向的地址都是常量池中的"abc"
         s3和s4指向的地址都是常量池中的"abcdef"
         s5和s3并不指向同一个地址,其实s5指向的是对象内存区,也就是s5其实指向了一个对象
         s6同理.

分析:
        字符串用"+"拼接的时候,如果是两个常量拼接,,不是通过某种方式将两个字符串的地址进行处理,连接两                   个字符串,而是直接产生一个由两个字符串拼接的新字符串常量;
        字符串用"+"拼接的时候,如果有变量参与拼接,则产生一个新对象

猜你喜欢

转载自blog.csdn.net/qq_34834846/article/details/81626022
今日推荐