![]() | Java Programming Preventing NullPointerException | Stack trace![]() |
NavigateExceptions topic:() |
NullPointerException
is aRuntimeException
. In Java, a specialnull
can be assigned to an object reference.NullPointerException
is thrown when an application attempts to use an object reference, having thenull
value.These include:
Throwable
, throwing a null reference.Applications should throw instances of this class to indicate other illegal uses of the null object.
![]() | Code section 6.13: Null pointer.Objectobj=null;obj.toString();// This statement will throw a NullPointerException |
The above code shows one of the pitfall of Java, and the most common source of bugs. No object is created and the compiler does not detect it.NullPointerException
is one of the most common exceptions thrown in Java.
null
?The reason we need it is because many times, we need to create an object reference before the object itself is created. Object references cannot exist without a value, so we assign thenull
value to it.
![]() | Code section 6.14: Non-instantiated declared object.publicPersongetPerson(booleanisWoman){Personperson=null;if(isWoman){person=createWoman();}else{person=createMan();}returnperson;} |
In thecode section 6.14 we want to create thePerson
inside the if-else, but we also want to return the object reference to the caller, so we need to create the object reference outside of the if-else, because of thescoping rule in Java. Incorrect error-handling and poor contract design can be a pitfall with any programming language. This is also true for Java.
Now we will describe how to preventNullPointerException
. It does not describe general techniques for how you should program Java. It is of some use, to make you more aware of null values, and to be more careful about generating them yourself.
This list is not complete — there are no rules for preventingNullPointerException
entirely in Java, because the standard libraries have to be used, and they can causeNullPointerException
s. Also, it is possible to observe an uninitialized final field in Java, so you can't even treat a final field as being completely trusted during the object's creation.
A good approach is to learn how to deal withNullPointerException
s first, and become competent with that. These suggestions will help you to cause lessNullPointerException
s, but they don't replace the need to know aboutNullPointerException
s.
When you compare a variable with a string literal, most of people would do that this way:
![]() | Code section 6.15: Bad comparison.if(state.equals("OK")){...} |
Always put the string literal first:
![]() | Code section 6.16: Better comparison.if("OK".equals(state)){...} |
If thestate
variable is null, you get aNullPointerException
in the first example, but not in the second one.
This means not doing things like:
![]() | Code section 6.17: Declaring an exception.Strings=null;while(something){if(something2){s="yep";}}if(s!=null){something3(s);} |
You can replace this with:
![]() | Code section 6.18: Declaring an exception.booleandone=false;while(!done&&something){if(something2){done=true;something3("yep");}} |
You might also consider replacing null with "" in the first example, but default values bring about bugs caused by default values being left in place. ANullPointerException
is actually better, as it allows the runtime to tell you about the bug, rather than just continue with a default value.
An array created usingnew Object[10]
has 10 null pointers. That's 10 more than we want, so use collections instead, or explicitly fill the array at initialization with:
![]() | Code section 6.19: Declaring an exception.Object[]objects={"blah",5,newFile("/usr/bin")}; |
or:
![]() | Code section 6.20: Declaring an exception.Object[]objects;objects=newObject[]{"blah",5,newFile("/usr/bin")}; |
Many methods that can return a reference can return a null reference. Make sure you check these. For example:
![]() | Code section 6.21: Declaring an exception.Filefile=newFile("/etc");File[]files=file.listFiles();if(files!=null){stuff} |
File.listFiles()
can return null if/etc
is not a directory.
You can decide to trust some methods not to return null, if you like, but that's an assumption you're making. Some methods that don't specify that they might return null, actually do, instead of throwing an exception.
Beware if you loop on an array or a collection in a for each loop.
![]() | Code section 6.22: Visit a collection.Collection<Integer>myNumbers=buildNumbers();for(IntegermyNumber:myNumbers){System.out.println(myNumber);} |
If the object is null, it does not just do zero loops, it throws a null pointer exception. So don't forget this case. Add anif
statement or return empty collections:
![]() | Code section 6.23: Visit a collection safety.Collection<Integer>myNumbers=buildNumbers();if(myNumbers!=null){for(IntegermyNumber:myNumbers){System.out.println(myNumber);}} |
There is tools like FindBugs that parse your code and warn you about potential bugs. Most of the time, it detects possible null pointers.
![]() | To do: |
![]() | Java Programming Preventing NullPointerException | Stack trace![]() |