Why toString() on an Object instance (which is null) is not throwing NPE?
The PrintStream#println(Object s)
method invokes the PrintStream#print(String s)
method, which first checks is the if the argument is null
and if it is, then just sets "null"
to be printed as a plain String
.
However, what is passed to the .print()
method is "null"
as String
, because the String.valueOf(String s)
returns "null"
before the .print()
method being invoked.
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
PrintWriter
's println(Object)
(which is the method called when you write System.out.println(nothingToHold)
) calls String.valueOf(x)
as explained in the Javadoc:
/**
* Prints an Object and then terminates 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.valueOf(Object)
converts the null to "null":
/**
* Returns the string representation of the <code>Object</code> argument.
*
* @param obj an <code>Object</code>.
* @return if the argument is <code>null</code>, then a string equal to
* <code>"null"</code>; otherwise, the value of
* <code>obj.toString()</code> is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj)