自己写代码的时候,第一次用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 = "";

 

相关文章:

  • 2022-12-23
  • 2021-05-19
  • 2021-05-20
  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
  • 2021-05-29
  • 2022-12-23
猜你喜欢
  • 2021-07-12
  • 2022-12-23
  • 2021-09-25
  • 2022-12-23
  • 2021-06-18
  • 2021-05-27
  • 2020-04-16
相关资源
相似解决方案