在String.concat方法中,参数不能是null,否则会抛出空指针异常。
如
String a = "hello ";
String b = null;
// 出现空指针异常
a.concat(b);
// 不会出现空指针异常 拼接结果为 "hello null"
a + b;
但是使用"+"进行拼接就不会出现异常。
在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);
}
方法体第一行中调用了length方法,所以参数不能为null。
使用idea查看时也能看到有个@NotNull