We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › NullPointerExeption
Page Index Toggle Pages: 1
NullPointerExeption? (Read 241 times)
NullPointerExeption?
Jan 5th, 2009, 8:38pm
 
I know this is a silly question, but if you don't ask you'll never learn..  

What is a NullPointerExeption? Something with a pointer not pointing to anything?  

Thanx
Re: NullPointerExeption?
Reply #1 - Jan 5th, 2009, 9:08pm
 
NullPointerException occurs when you try to perform an operation on an object variable that leads to null object.

The way to prevent this from happening is to check for null (probably not the best way, btw):

Code:

if(someObjectVariable != null){
// do something
}else{
// do nothing, or remedy the situation.
}
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.
Page Index Toggle Pages: 1