Why toString() on an Object instance (which is nul

2019-02-16 14:11发布

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?

4条回答
一夜七次
2楼-- · 2019-02-16 14:52

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)
查看更多
混吃等死
3楼-- · 2019-02-16 14:56

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.

查看更多
\"骚年 ilove
4楼-- · 2019-02-16 15:06

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);
}
查看更多
forever°为你锁心
5楼-- · 2019-02-16 15:14
    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"

查看更多
登录 后发表回答