Categories
Blog Tech

Java NullPointerException (NPE)? Quick FIX [Do this first!]7 min read

Here is the deal. This is the last time you will see the NullPointerException error. I promise… Sounds good? Let me tell you a secret that most other engineers have no clue about — a superpower to combat this error (and other errors as well).

You are a programmer and always after exact, to-the-point (no BS) solutions. When you encounter an error, you search Google in a blink of an eye and analyze & copy/paste only the relevant parts from StackOverflow (all happens lightning-fast).

This may surprise you, but I am like that as well… Still, this approach has one downside that hurts your head in the long run.

Let me explain this…

If you are routinely solving the errors without actually understanding the cause, you are bound to forget the solution… In a few weeks, you will hit the exact error again and will not remember how to fix it and what you did to solve it.

If you spend only 5 minutes reading this post till the end, you will understand the NullPointerException error in and out. (Learn it once — use it forever.)

No time is wasted on doing the same thing multiple times. See this as a good investment…

So read on.

What is causing the NullPointerException error in Java?

In simple terms, you are trying to access “something” that is not there (has no useful value)…

That “something” can be a variable, an object, a method, or an element of an array (some more options, but I don’t want to confuse you)…

Here comes the central part.

Look at the error itself: Null Pointer Exception. Think of it for a moment.

Exception simply means an error. So your code errored. Null is a value that you referenced (pointed to) somewhere in your code where some other (than null) value is expected.

Got it? Here are a few examples to make things crystal clear.


1. Declared variable with no value set upfront

In Java, you can declare a variable without specifying its value. Look at the code below.

int a;
int b = a + a;

Code line 1: Variable a has been declared (created), but no value has been assigned to it. What happens in the background is that Java automatically assigns the null value to the variable a.

Code line 2: Here, you are trying to do something with variable a. Specifically, you are creating a new variable b that “uses” variable a.

BOOOM. The null pointer exception error. Why?

Because the second line contains a reference (variable a) that points to the null value. (Points to the value of nothing.)

This example surfaces the core of the error. The exception is born when you reference the null value as if it was not the null but something else.

Let’s look at some other less obvious (and more challenging) examples. Read on.

2. Initialized object with “nothing” as a value

Look now at this example.

Integer availableCash;
availableCash = new Integer(10);Code language: JavaScript (javascript)

The first line defines an object of the Integer type and calls this object availableCash. You did not assign any value to the availableCash variable, so Java does it for you (automatically).

After the first line, the availableCash variable will have the null value.

In the second line, you are trying to manipulate the variable availableCash. Here, you are trying to assign it a new value.

Depending on your Java compiler, the code might give you the NullPointerException error or an error that says availableCash may not have been initialized.

LET’S MAKE ONE THING CLEAR.

Null as a value does not mean that there is no value. Contrary, it means that a variable has a value of Null. True, Null is a sort of “nothing,” BUT it is a regular value just as any other.

Make no mistake, and never think of null as undefined. It is there, it is defined, but it simply means “nothing.”

The limitations come when you try to use that null value in an inappropriate way. (In a way that assumes some other than the null value.)

3. Trigger a method on the null object

You may think an object has a non-null value and try to perform some “action” on it. Look at this now.

public class hashMeNow {

    public static void main(String[] args) {
        Object myObj = null;
        myObj.hashCode();
    }

}Code language: JavaScript (javascript)

I define a class called hashMeNow. Within the class, you see the void main part that executes when you run the code.

Next, myObj Object is initialized, and its value has been set to null. The following line myObj.hashCode() is supposed to return the hash value of myObj.

Since I deliberately set the value of myObj to null, the method hashCode() can only return the nullPointerException error as it cannot operate on the null objects.

The hashCode() method works only on the objects of the Integer type.

Your code is likely much more complex. Maybe you define an object somewhere else and drag it along until finally executing a method on it… To find out that the object has the value of null.

This is a very common setup that is considered to be your (programmer’s) mistake. Luckily enough, you can trace back the error and investigate why the object has the null value (when something else is expected).

4. Other causes of the nullPointerException error

Although I covered the most common ones, Java language specifications mention a few more situations that can lead to the error.

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.
https://oracle.docs.com

Here is the official nullPointerException documentation. If you need an explanation on any other cause, comment, and I will add it to the post.

How to quickly detect, fix, and avoid the NullPointerException error?

Yes, you can avoid it. I always recommend playing it safe and checking for the null value in your code.

Or you can wait for the disaster to come and catch you unprepared (your choice).

Here is how to check for the null value from the code directly.

    if(obj == null) {
       // Code that executes if the object has the null value
    } else {
       // Executes if it's of a non-null value
    }Code language: JavaScript (javascript)

If you work with legacy code bases, making the proper changes and avoiding the error can be hard. In those cases, it is all right if you see the notorious nullPointerException.

Use the stack trace (logs) to track the object across the files/classes until you find the spot where the object was misspecified (or wrongly specified).

Summary

Not all the errors are created equal. The nullPointerException error is one of the most common Java errors out there. (Want to know the most common Python error? Read more here.)

As the codebase grows, debugging it and understanding where things have gone south can be very impractical and hard.

You read here that the nullPointerException is a sort of a value error. In other words, you are doing something with a variable that assumes a value other than null.

With three different code examples, you discovered the root cause of more than 90% of the nullPointerException errors.

I did not stop there, but I also showed you a handy way to check for the null value in your code.

You are now equipped with some heavy machinery and are ready to fight the error on your field. Good luck.

P.S. Share your feelings (inclusive frustrations) about this error in the comment section.


Avatar photo

By Igor Jovanovic

Founder & Full Stack Tech Consultant

Experienced tech professional with a strong track record in web services and fintech. Collaborating with Silicon Valley's multi-billion tech giants and offering a range of services committed to excellence. Check the Services page for how I can help you too.

Leave a Reply

Your email address will not be published. Required fields are marked *