John Paterson wrote:Hi Folks,
I have this doubt.
In the above code, x.toString gives a NullPointerException. I believe this is due to the reference variable x not pointing anywhere as it's declared null.
That being the case, why is the line System.out.print(x) printing null to the console? Hope someone can explain why this difference. Thanks.
Accessing a null reference always causes the JVM to throw NPE.
The print method simply checks the input for null before invoking toString on it. If the input is null, it prints "null". That is why there is no NPE.