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

前端 未结 4 634
北荒
北荒 2021-01-04 05:41

Consider below one :

Object nothingToHold = null;

System.out.println(nothingToHold);  //  Safely prints \'null\'

Here, Sysout must be expe

相关标签:
4条回答
  • 2021-01-04 06:15

    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)
    
    0 讨论(0)
  • 2021-01-04 06:35
        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"

    0 讨论(0)
  • 2021-01-04 06:37

    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);
    }
    
    0 讨论(0)
  • 2021-01-04 06:39

    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.

    0 讨论(0)
提交回复
热议问题