Why doesn't toString () in an object instance (which is null) throw an NPE?

Consider below:

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

Here Sysout should expect String. Therefore, toString () must be called on an instance.

So why does null.toString () work amazingly? Does sysout care about this?

EDIT: Actually, I saw this weird thing with append () StringBuilder. So I tried with Sysout. Both behave the same. So does this method care?

+12
source share
5 answers

PrintWriter println(Object) (this is the method invoked when writing System.out.println(nothingToHold) ), calls String.valueOf(x) , as described in Javadoc:

 /** * Prints an Object and then terminates the line. This method calls * at first String.valueOf(x) to get the printed object 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 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) 
+18
source

The PrintStream#println(Object s) method calls PrintStream#print(String s) , which first checks to see if the argument is null , and if there is one, it simply sets "null" to print as a simple String .

However, what is passed to the .print() method is "null" as String , because String.valueOf(String s) returns "null" before the .print() method is called.

 public void print(String s) { if (s == null) { s = "null"; } write(s); } 
+8
source

Here is the documentation for println()

Prints a line followed by a new line. The string is converted to an array of bytes using the encoding selected when constructing this stream. Then the bytes are written to the target stream using write (INT).

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

NULL can convert to bytes.

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

This will display the output if NothingToHold (Object) is not null, otherwise it prints the message as "null String or something else"

0
source

Code speaks louder than words.

 class PrintStream { public void println(Object x) { String s = String.valueOf(x); // ... } } class String { public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); } } 
0
source

Source: https://habr.com/ru/post/984842/


All Articles