What Is A NullPointerException in Java? Let’s Understand And Learn How To Avoid It!

You are currently viewing What Is A NullPointerException in Java? Let’s Understand And Learn How To Avoid It!
Share This Post, Help Others, And Earn My Heartfelt Appreciation! :)
0
(0)

In this post I will present you one of the most common error in programming world. What Is A NullPointerException in Java? I will try to explain the topic, present many examples of use and I will try to use diagrams that easily (I hope) show what is happening under the hood in Java code and why you are getting NullPointerException error!

What Is A NullPointerException in Java?

When you try to use a reference that points to no location in memory (java null) as if it were addressing an object, you get a NullPointerException. NullPointerException is thrown when a method is called on a null reference or when a field of a null reference is accessed.

In other words: The NullPointerException arises when you declare a variable, but do not construct and assign an object to it before attempting to use the variable’s contents (called dereferencing). As a result, you’re pointing to something that doesn’t exist.

NullPointerException In Details (Java Null)

To present the topic easier, I will use an example. The following code shows a simple initialization of myString variable, which has a value of null as an assigned reference.

When we run this program, we will get the expected error. This is because we are trying to execute an object length method that does not exist in our computer memory. The program is unable to retrieve the value assigned to a given reference, so there is nothing to call the method on.

public class BigDataETLNullPointerException {

    public static void main(String[] args) {
        String myString = null; // Variable is the reference to memory
        System.out.println(myString.length());
    }
}

// Error output

Exception in thread "main" java.lang.NullPointerException
	at BigDataETLNullPointerException.main(BigDataETLNullPointerException.java:5)

Now check what’s going on under the hood. Take a look at the diagram below. I marked the reference to the computer memory with the arrow. You can see that the program is trying to find a nonexistent memory reference. What does not exist.

What Is A NullPointerException in Java?

Corrected Code

And now we will correct our above code to initialize the value of a myString variable. Thanks to this, an object of the String class will be created in the computer memory, to which we will have references in the form of the myString variable.

public class BigDataETLNullPointerException {

    public static void main(String[] args) {
        String myString = "BigData-ETL";
        System.out.println("The length of myString variable is : " + myString.length());
    }
}

// Output 
The length of myString variable is : 11

Explanation In The Diagram

As in the earlier part, let’s get used to the diagram what is the state of the computer’s memory. We can see that the reference (black arrow) now points to an object in the computer’s memory that exists, because we created it through initialization – assigning a value to it. This way, when we then execute the length method on our variable, the code will be successful.

What Is A NullPointerException in Java? Java null

Custom Class Example

Now let’s look at an example with any class. For this example, I created a Point class that has two variables: x, y and @Override toString method:

public class Point {
    private Integer x;
    private Integer y;

    public Point(Integer x, Integer y) {
        this.x = x;
        this.y = y;
    }

    public Integer getX() {
        return x;
    }

    public Integer getY() {
        return y;
    }

    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}

Next, we will try to initialize the Point object and call the toString method. In this case, IDEA will not even let you execute the ego code, because already at the compilation level you will get an error:

java: variable pointB might not have been initialized
public class BigDataETLNullPointerException {

    public static void main(String[] args) {
        Point pointA = new Point(10, 10);
        System.out.println(pointA);

        Point pointB;
        System.out.println(pointB);

    }
}

Make It Harder

Now we’ll do it so that on the compile level everything will be ok and they have not received any error. Let’s create a helper method createNewPointBasedOn. This method takes Point as a parameter and based on it will return a new point where we add +5 to each of its variables.

    private static Point createNewPointBasedOn(Point point) {
        return new Point(point.getX() + 5, point.getY() + 5);
    }

Now let’s try this method:

public class BigDataETLNullPointerException {

    public static void main(String[] args) {
        Point pointA = new Point(null, 10);
        Point pointB = createNewPointBasedOn(pointA);
        System.out.println(pointB);
    }

    private static Point createNewPointBasedOn(Point point) {
        return new Point(point.getX() + 5, point.getY() + 5);
    }
}

// Output, Exception:
Exception in thread "main" java.lang.NullPointerException
	at BigDataETLNullPointerException.createNewPointBasedOn(BigDataETLNullPointerException.java:10)
	at BigDataETLNullPointerException.main(BigDataETLNullPointerException.java:5)

Summary

Hopefully now, if you get a NullPointerException error i Java, you’ll know what’s causing it.
The hardest thing to do in this case is to find out why, we get null somewhere in the code.


The best way to avoid these types of errors is to use proper error handling and avoid nulls. Consider how to write better methods / functions to never get null.

A good practice is to wrap values that are summarized as Option objects. And an even better solution is to foresee what may go wrong in the code and redirect it accordingly, which is to use the Either concept. But I will write about it in another article. We also encourage you to follow the news or use the search magnifier in the top right corner of the blog.

The best way to find a null spot in the code is to run the program in Debug. Then we are able to trace the code and see at selected stages of the program execution what value each object has. We can catch a mistake in the act!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments