Consider the following code:
Okay..I am totally confused. Why does line 1 print null, and line 2 causes expection..
Here is what I think, please correct me if I am wrong.
Thomas posted:
The print(Object obj) method of PrintWriter runs the String.valueOf(Object obj) method. Whta does that method do? It has one instruction:
return (obj == null) ? "null" : obj.toString();
So if the passed in Object is null, it returns the String "null" otherwise it runs the toString method of the Object.
So, line 1 prints null.
But in line 2 we are forcefully calling toString() for the object. Since the object is null, an expection occurs, since we are calling a method on a null object.
Thanks.