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?
Example using a null check Very often in programming, a String is assigned null to represent that it is completely free and will be used for a specific purpose in the program. If you perform any operation or call a method on a null String, it throws the java. lang. NullPointerException.
ToString(null) returns a null value, not an empty string (this can be verified by calling Convert. ToString(null) == null , which returns true ).
It essentially means that the object's reference variable is not pointing anywhere and refers to nothing or 'null'. In the given example, String s has been declared but not initialized. When we try to access it in the next statement s. toString() , we get the NullPointerException.
The toString() method is overridden in the class. A null value and an optional string argument are passed to the method. The method should return default string as the input object is null .
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)
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With