Java中字符串拼接+和concat有什么区别呢?
下文笔者讲述"+"和concat拼接字符串的区别说明,如下所示
例:"+"和concat拼接字符串的示例
例:"+"和concat拼接字符串的示例
public static void main(String[] args) {
// example1
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
// example2
String str3 = "s3";
System.out.println(str3 + null);//s3null
System.out.println(null + str3);//nulls3
String str4 = null;
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[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
"+"和concat拼接字符串区别
+: 字符串或数字及其它基本类型数据 concat: 只能接收字符串 +:左右可以为null concat:空指针会报错
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


