Kacper Kacper - 25 days ago 3
Java Question

Why does System.out.print on null object work?

Let's consider following code:

public static void main(String[] args) {
Integer i = null;
Object o = null;

System.out.println(i);
System.out.println(o);

System.out.println(i.toString());
System.out.println(o.toString());
}


That's quite obvious that last two prints will cause
NullPointerException
. One can't call method on null object.

The question is why first two prints work? Aren't they calling
toString()
as well?

Answer

No they aren't.

System.out is a PrintStream and it calls String.valueOf(x) on the argument (as described in the the Javadoc).