String字符串拼接符 “+”底层原理

  1. 字符串常量的拼接

    		String str3="hello"+" word!";
    		String str4="hello word!";
    		System.out.println(str3==str4);
    		//运行结果:true
    原因:JVM编译器对字符串做了优化,在编译时str3就已经被优化成“hello Word!”,str3和str4指向字符串常量池同一个字符串常量,所以==比较为true。


  2. 字符串+字符串变量、字符串变量之间的拼接。

    		String str1="hello";
    		String str2=" word!";
    		String str3="hello word!";
    		String str4=str1+"word!";
    		System.out.println(str3==str4);
    		//运行结果为false

    原因:字符串拼接时如果有字符串变量参与拼接,底层调用了StringBuffer可变字符串处理。代码如下
    		StringBuffer sb=new StringBuffer("");
    		sb.append(str1);
    		sb.append("word!");
    		str4= sb.toString();
    //StringBuffer的toString()方法底层new了一个String对象,所以str4在堆内存中重新开辟了空间,
    //str3指向常量池,所以为false
    


版权声明:本文为yin_xiangkun原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。