I ran the following code
String str = null;
System.out.println(str);
Output was null.
At first, I thought that the NullPointerException
will be thrown as printing the object implicitly calls toString
method. So, I was surprised with the output.
Then I contemplated about the output and thought that above String statement actually didn't create any object, only reference is created that doesn't point to any object. So that may be the reason of such output.
Can somebody please let me know if my understanding is correct.
The print()
methods explicitly check for null
.
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