Skip to main content

What is a NullPointerException? And how to fix it?


When you declare a reference variable (object) you are actually making a pointer to an object.
Consider a variable of primitive type int:

int x;
x = 10;

In this sample, the variable x is an int and Java will initialize it to 0 for you. When you allocate it the value of 10 on the next line, your value of 10 is written into the memory location denoted by x.

But, when you attempt to declare a reference type, slightly different happens.
Take the following code:

Integer num;
num = new Integer(10);

The 1st declares a variable named num, but it does not truly hold a primitive value yet. In its place, it has a pointer (because the type is Integer which is a reference type). Meanwhile you have not yet said what to point to, Java sets it to null, which means "I am pointing to nothing".

In the 2nd line, the new keyword is used to instantiate (or generate) an object of type Integer and the pointer variable num is allocated to that Integer object.

The NullPointerException happens when you declare a variable but did not make an object. So you are pointing to something that does not really exist.

If you try to dereference num before creating the object you get a NullPointerException. In small cases, the compiler will catch the problem and let you know that "num may not have been initialized," but occasionally you may write code that does not straightly create the object.

For instance, you may have a method as:

public void doSomething(SomeObject obj) {
   //do something to obj
}

In which case, you are not making the object obj, but somewhat assuming that it was created beforehand the doSomething() method was called.
Note, it is likely to call the method like this:

doSomething(null);

In which circumstance, obj is null. If the method is planned to do something to the passed-in object, it is valid to throw the NullPointerException because it's a programmer error and the programmer will need that info for debugging purposes.

Otherwise, there may be cases where the purpose of the method is not only to work on the passed in object, and hence a null parameter may be acceptable. In this case, you would need to check for a null parameter and act differently. You should also clarify this in the documentation.
For example, doSomething() could be written as:

/**
  * @param obj An optional foo for ____. May be null, in which case
  *  the result will be ____.
  */
public void doSomething(SomeObject obj) {
    if(obj != null) {
       //do something
    } else {
       //do something else
    }
}

Comments