×

Loading...

Q. Jabber, it seems I have understood what you said. Can you give a more complicated example?

本文发表在 rolia.net 枫下论坛A: Yes. After we declare a varable, we don't alway create a new object and assign it to the variable. Often, we get a referece to another Object by calling some other methed of some other Object, and then assign this refernce to our newly declared variable name.

//other code
Hashtable ht = new Hashtable();
ht.put("name", "John");
String s1= ( (String)ht.get("name") ).toUpperCase();
System.out.println(s1);
String s2= ( (String)ht.get("age") ).toUpperCase();
System.out.println(s2);
//other

If you test this code, you will see "JOHN" being printed out and then an NullPointerException being thrown.

The reason is that you get a null as you try to get "age" from the Hashtable ht. Since it is a null, how can you call its toUpperCase() method? So the code fails at the last but two line.

In Java library, many motheds return an Object referece in the normal case and a null in the abnormal case. If the execution your code run into the abnormal case, the
NullPointerException brings you some trouble. This is where complexities arise.更多精彩文章及讨论,请光临枫下论坛 rolia.net
Sign in and Reply Report

Replies, comments and Discussions: