字符串拼接+和concat的区别
字符串拼接+和concat的区别
+和concat都可以用来拼接字符串,但在使用上有什么区别呢,先来看看这个例子。
public static void main(String[] args){
String str1="s1";
System.out.println(str1 + 100);//s1100
System.out.println(100 + str1);//100s1
String str2="s2";
str2 = str2.concat("a").concat("bc");
System.out.println(str2);//s2abc
String str3="s3";
System.out.println(str3 + null);//s3null
System.out.println(null + str3);//nulls3
String str4="s4";
System.out.println(str4.concat("a"));//NullPointerException
System.out.println("a".concat(str4));//NullPointerException
}
concat源码:
public String concat(String str){
int otherLen=str.length();
if(otherLen==0){
return this;
}
int len=value.length;
char buf[]=Array.copyOf(value,len+otherLen);
str.getChars(buf,len);
return new String(buf,true);
}
所以可以得出以下结论:
+可以是字符串或者数字及其他基本类型数据,而concat只能接收字符串。
+左右可以为null,concat为会空指针。
如果拼接空字符串,concat会稍快,在速度上两者可以忽略不计,如果拼接更多字符串建议用StringBuilder。
从字节码来看+号编译后就是使用了StringBuiler来拼接,所以一行+++的语句就会创建一个StringBuilder,多条+++语句就会创建多个,所以为什么建议用StringBuilder的原因。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?