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

前端 未结 4 658
北荒
北荒 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 {@link #print(String)} and then
     * {@link #println()}.
     *
     * @param x  The Object to be printed.
     */
    public void println(Object x)
    

    String.valueOf(Object) converts the null to "null":

    /**
     * Returns the string representation of the Object argument.
     *
     * @param   obj   an Object.
     * @return  if the argument is null, then a string equal to
     *          "null"; otherwise, the value of
     *          obj.toString() is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj)
    

提交回复
热议问题