Probably one of the most common and annoying exceptions to be encountered by any Java developer is the dreaded “NullPointerException”. A null pointer exception is thrown when an “illegal” referencing of a null object is performed. A “null” object is an object which is not initialized. Let us explore some examples of how a null pointer exception can be caused.

Let us take the PostCategory class for our null pointy examples below:

 

Situation 1 – null value provided:

This situation usually occurs when the caller of the method provides a null value such as in the example below:

 

The main method here calls the testNull1 method with a null value. Inside the method, we try to dereference the category value that was passed to us. However, since the caller provided a null, Java would complain with a null pointer exception

 

It is a good practice to handle null objects to avoid an application crash, while informing the end user that something went wrong.
Sometimes, obtaining a null value is can be an expected and normal behavior of an application.

For example, let us say the user calls a function that searches the database for a “Category” object. If we find the object, then we would display its contents. Sometimes the user may search using the wrong name or id and we would obtain a null from the database. In that case we would like to inform the user that the object was not found.

 

Situation 2 – Object is initialized, but inner variable is null:

This example builds upon the previous one by trying to dereference a null internal variable. Take for example the “description” member of the PostCategory class. Let us say we want to our program to print out the number of characters in the category description. It would look something like this:

 

Running this program would causes it to break when calling the “.lenght()” method, because here tried to dereference a null object, namely the description. The following is the program output:

 

 

The same situation applies if we access null members of arrays, or even inner members of inner members of inner… of an object. Once has to be careful with handling object references and we need to make sure that if a NullPointerException is possible in one place, that this possibility is taken care off. You never know when data from database or a file could go missing!