×

Loading...
Ad by
  • 最优利率和cashback可以申请特批,好信用好收入offer更好。请点链接扫码加微信咨询,Scotiabank -- Nick Zhang 6478812600。
Ad by
  • 最优利率和cashback可以申请特批,好信用好收入offer更好。请点链接扫码加微信咨询,Scotiabank -- Nick Zhang 6478812600。

Nothing can be taken for granted

本文发表在 rolia.net 枫下论坛Thanks a million for long-river and guest's posting. My postings are essentially for laymen and novices. Obviously, NullPointerException is a trivial one and
can be easily handled by a true Java programmer.
Guest pointed out the general solution:
Check if the Object reference is null before
you call its methods. For instance, people
need check if a network connection or dababase connection is still there before you call its corresponding close() method.

Another kinds of example is related to some
deprecated methods, which usually return a null in a server that implements a higher version of API. For instance, in most Java servlet engine that implements servlet API 2.2, if you run a servlet that uses getServlet method of the ServletContext interface, you will get a null. In the server-side Java programming, you don't always have luck to
see the StackTrace of a NullPointerException.

It seems to me nothing is really simple in this world. I have ever witnessed many Java learners stunned before NullPointerException. For a beginner, it is not straightforward to understand NullPointerException, let alone handling it gracefully.更多精彩文章及讨论,请光临枫下论坛 rolia.net
Sign in and Reply Report

Replies, comments and Discussions:

  • 工作学习 / IT技术讨论 / Java Q&A (2) (compiled by jabber)
    • About NullPoiterException.
      本文发表在 rolia.net 枫下论坛Q: Jabber, I frequently get a NullPoiterException but I did not understand why. Can you say something about it?

      A: Yes. Let me first give you an example in the real life. John and Mary decided to have a baby next year. And they have decided to give it a name "Mark" if it turns out to be a boy. We know a baby can smill and cry. Because Mary is so eager to have a baby, she often says:

      Mark, smile!
      Mark, smile!
      Mark, smile!

      Let me ask you a stupid question: As Mary says "Mark, smile!", will "that baby" smile???

      No! The reason is that the baby have not yet been borne. This is exactly a NullPoiterException---Mark is not related to some concrete, existing baby. Before the baby is born, you cannot ask it smile.

      In Java, programmers uaually first declare a varable name, then create an object instance using "new", next assign this instance to the variable. After that, you can call mathods through variable name. This sounds like:

      //other code
      Child child= new Child("Mark");
      child.smile();
      // other code, we assume we have a class Child defined somewhere else

      The above cold is OK. However, the following code will throw NullPointerExpecetion:

      //other code
      Child child =null;
      child.smile();
      //other code

      The reason is that you just hold a variable name "child" for the futire use and have not yet
      related to any existing Child.更多精彩文章及讨论,请光临枫下论坛 rolia.net
      • a very good explaination. May I have some suggestion
        for your example so that it looks better?

        change

        //other code
        Child child= new Child("Mark");
        child.smile();
        // other code, we assume we have a class Child defined somewhere else

        to

        //other code
        Child realChild= new Child("Mark");
        realChild.smile();
        // other code, we assume we have a class Child defined somewhere else
      • nullpointerexception
        Any java programmer knows that he has to create an instance of the child class. So one of the reason why getting nullpointerexception is

        if you code a condition like this

        if (xxx==10) {
        ...
        }

        while the complier finds that the value is null, the npex appears. Possible solution is to use

        if (xxx!=null) first to avoid it.
        • Nothing can be taken for granted
          本文发表在 rolia.net 枫下论坛Thanks a million for long-river and guest's posting. My postings are essentially for laymen and novices. Obviously, NullPointerException is a trivial one and
          can be easily handled by a true Java programmer.
          Guest pointed out the general solution:
          Check if the Object reference is null before
          you call its methods. For instance, people
          need check if a network connection or dababase connection is still there before you call its corresponding close() method.

          Another kinds of example is related to some
          deprecated methods, which usually return a null in a server that implements a higher version of API. For instance, in most Java servlet engine that implements servlet API 2.2, if you run a servlet that uses getServlet method of the ServletContext interface, you will get a null. In the server-side Java programming, you don't always have luck to
          see the StackTrace of a NullPointerException.

          It seems to me nothing is really simple in this world. I have ever witnessed many Java learners stunned before NullPointerException. For a beginner, it is not straightforward to understand NullPointerException, let alone handling it gracefully.更多精彩文章及讨论,请光临枫下论坛 rolia.net
    • 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
    • I got an effor message saying "....java.lang.NoClassDefFoundError:...".
      本文发表在 rolia.net 枫下论坛Q: I am trying to learn Java. I copied a Hello.java example to C:\sources and then succeeded in compiling the course file into the class file. Then, I tried to run this example by entering "java Hello". However, I got an effor message saying "....java.lang.NoClassDefFoundError:...". What's wrong?

      A: Very probably, your Windows envirenment variable CLASSPATH does not include ".", --- the current directory. To execute your command "java Hello", Java Virtual Machine needs to search the class file Hello.class according to CLASSPATH. If it fails to find the class file, it will complain by throwing the message you cited. For a Java programmer, it is a good practice to include the current directory in the CLASSPATH.

      To make your example work, you can reset the CLASSPATH by issuing

      "set CLASSPATH=.;%CLASSPATH%"

      in the MS-DOS. The above command means to append . (the current directory) to the CLASSPATH.

      Note: Windowes envirment variable should be sandwished by a pair of percentage signs (%). After you reset the CLASSPATH, you will have luck to run your example.

      PATH and CLASSPATH are two most basic environment variables for Java programmers. Even seasoned Java developers can get into dark with them. A Java novice needs to make many mistakes with them before mastering them.更多精彩文章及讨论,请光临枫下论坛 rolia.net
    • About final constants in Java library classes
      本文发表在 rolia.net 枫下论坛Q: I see that some Java library classes define some final constants. By curiosity, I printed out some of these final constants using "System.out.println(...)". I observed that most of these constants are just simple numbers such 0, 1, 2. Why other to define them?

      A: If you use 0, 1 , 2 ... directly in the code, you may forget what they mean in a few days. In addition, the same number can stand for different things in a different contexts.

      Hence, people usuall call these numbers "magic numbers". Remember this world, it will help to talk Java as a native Canadian does.

      Ia a real project, it is a common practice to define an interface to hold all the final constants.

      For instance, if you buikd a Web site using Java servlet and JSP, you can define an interface called PageNames to collect all the page names. By doing so, you can avoid hard-code pages in your source files so that they can be easily maintained. In a job interview, I have been asked: Where is the good place to define constants for a project?更多精彩文章及讨论,请光临枫下论坛 rolia.net
    • New java programmer also. I get much help from those posts, keep posting. Thanks
      • Gentle person, I have been flattered.