Why toString() on an Object instance (which is null) is not throwing NPE?

眉间皱痕 提交于 2020-01-21 04:15:30

问题


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?


回答1:


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)



回答2:


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);
}



回答3:


Here is documentation for println()

Prints a string followed by a newline. The string is converted to an array of bytes using the encoding chosen during the construction of this stream. The bytes are then written to the target stream with write(int).

If an I/O error occurs, this stream's error state is set to true.

NULL can convert to bytes.




回答4:


    Object nothingToHold = null;
   System.out.println(nothingToHold != null ? nothingToHold : "null String or any thing else");

This will display output if the nothingToHold(Object) not equals to null, otherwise it prints the message as "null String or any thing else"



来源:https://stackoverflow.com/questions/29513497/why-tostring-on-an-object-instance-which-is-null-is-not-throwing-npe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!