java 字符串拼接为什么不能用null

自己写代码的时候,第一次用String str= null;然后去拼接字符串,在查询的时候报错,debug检查出来,最终的参数字符串str里面居然有null,如图:

java 字符串拼接为什么不能用null

 

所以拼接字符串不能用null,原因如下:

s = s+"word"; 等价于 s = String.valueOf(s)+"word";  Integer,Double都一样。

//jdk源码
public static String valueOf(Object obj) {
  return (obj == null) ? "null" : obj.toString();
}

在这里就已经返回一个null了,但如果定义为如下呢?自己去试试吧。

String str = "";