Consider below one :
Object nothingToHold = null;
System.out.println(nothingToHold); // Safely prints 'null'
Here, Sysout must be expecting String. So toString() must be getting invoked on instance.
So why null.toString() works awesome? Is Sysout taking care of this?
EDIT : Actually I saw this weird thing with the append() of StringBuilder. So tried with Sysout. Both behave in the same way. So is that method also taking care?
PrintWriter
'sprintln(Object)
(which is the method called when you writeSystem.out.println(nothingToHold)
) callsString.valueOf(x)
as explained in the Javadoc:String.valueOf(Object)
converts the null to "null":Here is documentation for
println()
NULL
can convert to bytes.The
PrintStream#println(Object s)
method invokes thePrintStream#print(String s)
method, which first checks is the if the argument isnull
and if it is, then just sets"null"
to be printed as a plainString
.However, what is passed to the
.print()
method is"null"
asString
, because theString.valueOf(String s)
returns"null"
before the.print()
method being invoked.This will display output if the nothingToHold(Object) not equals to null, otherwise it prints the message as "null String or any thing else"