Read a lot on the Web. When you print an object directly from Java, call the ToString method of the class directly.
But:
Object Obj=null; System.out.println (obj);//No error System.out.println (obj.tostring ());//Report NULL pointer exception
System.out.println (obj); since it is also called the ToString method directly, why not error???
The reasons are summarized as follows:
1. Call the ToString method of the object class, you must ensure that object is not a null value, or the NullPointerException exception will be thrown.
2.SYSTEM.OUT.PRINTLN () source code is as follows:(that is, you will first determine whether it is null, NOT NULL to call the ToString () method)
public void println (Object x) { String s = string.valueof (x); Synchronized (this) { print (s); NewLine (); } } public static String valueOf (Object obj) {return (obj = = null)? "Null": Obj.tostring (); }
public void print (String s) {if (s = = null) { s = "null";} Write (s); }
Related Detailed blog: http://m.blog.csdn.net/article/details?id=44727535
Original!! When Java prints an object directly, it does not call the ToString method of the class directly, but it first determines whether it is null and NOT NULL to call the ToString method