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!