What is a NullPointerException in Java

In this post we will explain what is a NullPointerException in Java, and how to fix these issues.

What is a NullPointerException in Java

An application will throw a null pointer exception when you are invoking a method on an object who’s value is null. Lets have a look at the example below.

Running the above code sample, produces the following output

A few points to note

  1. The noValue variable is null
  2. The NullPointerException is thrown when invoking the contains() method on the null object – noValue.

To avoid this issue you will need to assign a value to the noValue variable as seen in the example below.

Running the above code produces the following:

As you can see from the output no exception was thrown.

I hope this post has helped you understand what is a NullPointerException and how to avoid it from happening.

Similar posts:

  1. How to create custom exception in Java
  2. Handle an exception thrown by callable
  3. How to create a Thread in Java
  4. Java String basics

References:

  1. NullPointerException API Documentation

 

Leave a Reply