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

前端 未结 4 662
北荒
北荒 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: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);
    }
    

提交回复
热议问题