Java String是如何输出NULL的
2021-03-25 本文已影响0人
atdoking
1、对于申明的变量为String类型的,若其为空null,打印为空


主要在于print方法的实现,println方法是print和newline方法一起达到目的的,看源码可以发现
/**
* Prints a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>String</code> to be printed.
*/
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
print方法内部,当判断为空时,则赋值一个null字符串给变量,然后输出
/**
* 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);
}
2、对于申明的变量是一个非String类型的Object时,打印还是null

其原因还是print方法的另一个不同类型参数的重载实现,其内部会将该对应的转换成字符串,然后print方法内部,当判断为空时,则赋值一个null字符串给变量,然后输出
/**
* Prints an Object and then terminate the line. This method calls
* at first String.valueOf(x) to get the printed object's string value,
* then behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>Object</code> to be printed.
*/
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
对于不同类型的其他变量,打印输出也大致是这个思路,然后打印出null