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

system (_)
本文发表在 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.

//other code
Hashtable ht = new Hashtable();
ht.put("name", "John");
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
2000-9-4 -05:00
This post has been archived. It cannot be replied.
Page address has been copied.
To share, click to copy page address.
Share Online by QR Code

Back To Topic: Java Q&A (2) (compiled by jabber)

Back To Forum: HOME枫下论坛枫下论坛主坛工作学习IT技术讨论