本文发表在 rolia.net/zh 相约加拿大网上社区枫下论坛
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.
Hashtable ht = new Hashtable();
String s1= ( (String)ht.get("name") ).toUpperCase();
String s2= ( (String)ht.get("age") ).toUpperCase();
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/zh
This post has been archived. It cannot be replied.