更多 Java 基礎知識方面的文章械筛,請參見文集《Java 基礎知識》
打印 null 字符串
示例:
String str = null;
System.out.println(str); // null
原因分析:PrintStream
類中包含如下代碼入撒,做了 null
的特殊判斷
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
打印 null 對象
示例:
Object obj = null;
System.out.println(obj); // null
原因分析:PrintStream
類中包含如下代碼,將對象轉換成字符串
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
而 String
類中的 valueOf
方法定義如下,做了 null
的特殊判斷:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
打印 null 對象與字符串拼接
示例:
String s = null + "123";
System.out.println(s); // null123
原因分析:
編譯器對字符串相加會進行優(yōu)化,首先實例化一個 StringBuilder
遮精,然后把相加的字符串按順序 append
,最后調用 toString
返回一個 String
對象败潦。
StringBuilder
中的 append
方法做了 null
的特殊判斷本冲,如下:
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
private AbstractStringBuilder appendNull() {
int c = count;
ensureCapacityInternal(c + 4);
final char[] value = this.value;
value[c++] = 'n';
value[c++] = 'u';
value[c++] = 'l';
value[c++] = 'l';
count = c;
return this;
}