查看原文
其他

字符串拼接+和concat的区别

2017-09-13 javastack Java技术栈


+和concat都可以用来拼接字符串,但在使用上有什么区别呢,先来看看这个例子。

  1. public static void main(String[] args) {

  2.    // example1

  3.    String str1 = "s1";

  4.    System.out.println(str1 + 100);//s1100

  5.    System.out.println(100 + str1);//100s1

  6.    String str2 = "s2";

  7.    str2 = str2.concat("a").concat("bc");

  8.    System.out.println(str2);//s2abc


  9.    // example2

  10.    String str3 = "s3";

  11.    System.out.println(str3 + null);//s3null

  12.    System.out.println(null + str3);//nulls3

  13.    String str4 = null;

  14.    System.out.println(str4.concat("a"));//NullPointerException

  15.    System.out.println("a".concat(str4));//NullPointerException

  16. }

concat源码:

  1. public String concat(String str) {

  2.    int otherLen = str.length();

  3.    if (otherLen == 0) {

  4.        return this;

  5.    }

  6.    int len = value.length;

  7.    char buf[] = Arrays.copyOf(value, len + otherLen);

  8.    str.getChars(buf, len);

  9.    return new String(buf, true);

  10. }

看下生成的字节码:

所以可以得出以下结论:

  • +可以是字符串或者数字及其他基本类型数据,而concat只能接收字符串。

  • +左右可以为null,concat为会空指针。

  • 如果拼接空字符串,concat会稍快,在速度上两者可以忽略不计,如果拼接更多字符串建议用StringBuilder。

  • 从字节码来看+号编译后就是使用了StringBuiler来拼接,所以一行+++的语句就会创建一个StringBuilder,多条+++语句就会创建多个,所以为什么建议用StringBuilder的原因。

看完有没有收获?

分享到朋友圈给更多的人吧。





    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存