GritHub

String 类中 concat() 方法和 + 号的区别:

pubic class Demo{
    pulic satic void main(String[] args){
        String str1 = "a".concat("b").concat("c");
        String str2 = "a"+"b"+"c";
        String str3 = "abc";
        String str4 = new String("abc");
        System.out.println(str1 == str2); //运行结果为false
        System.out.println(str1 == str3); //运行结果为false
        System.out.println(str2 == str3); //运行结果为ture
        System.out.println(str2 == str4); //运行结果为false
        System.out.println(str1.equals(str4)); //运行结果为true
    }
}

执行结果为:

false
false
true
false
true

解析:

首先关于 new 出来的对象和 String s = "字符串" 的 == 执行结果为 false 就不多赘述了,因为 == 比较的是两个对象的地址值,equals() 比较的是字面值。那么 concat 方法和 + 号的区别在这里有体现了,我们查看concat方法的源码可以看到,它是通过复制数组在通过 char 数组进行拼接生成一个新的对象,所以地址值会有变动,而 + 号不会。(作者很菜,初来乍到,前辈多包涵)