PhiLho
Re: NullPointerExeption?
Reply #2 - Jan 6th , 2009, 10:36am
The name is strange, now that I think of it, because officially Java has no pointers, unlike C or C++ (I don't know for C#). I suppose the pointers are internal, or figurative (being offset or something). Anyway, sw01 is right, of course. A common case is to get an object from a method call, and this method might return null to indicate a problem/an error. If you try to use a method of the returned object without first checking it, you will get this runtime error: SomeObj o = getSomeObj(param); o.doSomething(); <-- NPE is possible here! As pointed out, a solution is to check against null value. You often see idioms like: if (o != null && o.isSomething()) for example. It uses shortcut evaluation, ie. if first part is false, second part won't be evaluated because we are sure the whole expression will be false anyway. These tests can become heavy, so some people say you should return a so-called null-object, which is actually an "empty" object. The concept varies with the kind of object, and might not be always possible actually. A common case is when the method returns an array: instead of returning null, it returns an empty array (eg.: return new SomeObj[0]; Thus, if you loop on the array later, the loop is skipped, the length() being zero. For collections, you can return Collections.EMPTY_LIST, Collections.EMPTY_MAP or Collections.EMPTY_SET, depending on type. Of course, another solution is to throw an exception in case of error, but that's another problem.