字符串拼接+和concat的区别

本文通过示例对比了Java中字符串拼接符号+与concat方法的不同之处,包括它们对于不同类型参数的处理方式及性能差异,并给出了在不同场景下的使用建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                             字符串拼接+和concat的区别


+和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的原因。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值