Tostring method that is easy to ignore

Source: Internet
Author: User

First look at a program
/*
* Created on 2005-2-24
*/

/**
* @ Author snowway
*/
Public Class {

Private string ID;

Public String tostring (){
Return this. ID;
}

Public static void main (string [] ARGs ){
System. Out. println (new ());
}
}

I thought it would print null, and the running result is:
Exception in thread "Main" Java. Lang. nullpointerexception
At java. Io. Writer. Write (reader. Java: 126)
At java. Io. printstream. Write (printstream. Java: 457)
At java. Io. printstream. Print (printstream. Java: 616)
At java. Io. printstream. println (printstream. Java: 753)
At a. Main (A. Java: 17)

After careful debugging, we can see that the process is like this:
First, call the printstream. println (object) method. println (object) calls the printstream. Print (object) method. This method uses string. valueof (object)
Obtain the string output of an object. Let's look at the source code of string. valueof (Object OBJ:
Public static string valueof (Object OBJ ){
Return (OBJ = NULL )? "Null": obj. tostring ();
}
No problem, because we passed new ()! = NULL, so call New A (). tostring (), then tostring returns this. ID, obviously null,
Finally, println calls write (STR, 0,Str. Length ()); Haha, the problem is coming out. Str = NULL, so Str. length is obviously to throw NPE.

The lesson is: Never let the tostring method of the class return null!

 

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.