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

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.