In println, here o.toString() throws NPE but o1, does not. Why?
public class RefTest {
public static void main(String[] args) {
Object o = null;
Object o1 = null;
System.out.println(o.toString()); //throws NPE
System.out.print(o1); // does not throw NPE
}
}
It might help showing you the bytecode. Take a look at the following
javapoutput of your class:Just looking at the main method, you can see the lines of interest are where
Codeis 8 and 33.Code 8 shows the bytecode for you calling
o.toString(). Hereoisnulland so any attempt on a method invocation onnullresults in aNullPointerException.Code 18 shows your
nullobject being passed as a parameter to thePrintStream.print()method. Looking at the source code for this method will show you why this does not result in the NPE:and
String.valueOf()will do this withnulls:So you can see there is a test there which deals with
null, and prevents an NPE.