String a = null;
System.out.println(a+"1");
输出为null1
@depress 说的很好,补充下为什么会调用String.valueOf,其实“+”这个运算符可以看做是一个语法糖,对于C++开发者来说可能会觉得是操作符重载了,其实在java中是没有重载的,通过反编译.class文件可以看到其会调用java.lang.StringBuilder#append(java.lang.Object)这个方法,所以就会产生depress所说的那种情形。
看下官方的说明吧。
http://docs.oracle.com/javase...
If the reference is null, it is converted to the string "null" (four
ASCII characters n, u, l, l).
jdk 源码 :
/**
* Prints a string. If the argument is <code>null</code> then the string
* <code>"null"</code> is printed. Otherwise, the string's characters are
* converted into bytes according to the platform's default character
* encoding, and these bytes are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
*
* @param s The <code>String</code> to be printed
*/
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
4 回答970 阅读
4 回答887 阅读
586 阅读
492 阅读
a+"1"等同于String.valueOf(a)+"1",不只是String,当a为Integer和Double时都如此。
而
当String对象为空时返回字符串null,这下知道为什么了吧。