What is Null Pointer Exception in Java and How to Fix it?

If must have faced java.lang.NullPointerException while writing code in any programming language. In this post, we will discuss on “What is Null Pointer Exception in Java and how to fix it.”

Java throws Null Pointer Exception only during runtime when an application tries to use object reference which is null. Let’s try to understand through an example.

Null Pointer Exception in Java

The above program compiles with no error. But when the program is executed, it gives the below exception.

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

In java, the reference variables (obj in this example) are pointers to objects. In the above example, the reference variable obj is instantiated with null which means “it is pointing to nothing”.  During runtime when java tries to use the reference variable which really is not pointing to anything, it gives a Null Pointer Exception i.e. the reference variable in use is pointing to nothing or null.

Read also: Difference between Java and JavaScript

Now that you understand what is null pointer exception, it is necessary to understand that it can be caused due to improper usage and here I will explain what can cause null pointer exception with following examples:

Example 1:

When you compare a String with a literal without assigning a non-null value.

Null Pointer Exception Example

The code will throw the error as below:
Exception in thread "main" java.lang.NullPointerException at HelloWorld.main(HelloWorld.java:5)

To avoid null pointer in such situation we can call equals on the literal rather than the String reference as shown below:

Handle Java NullPointerException

Example 2:

“Prevention is better than cure”, so it’s better if we can add null checks to methods wherever null is possible. But you should not do it unnecessarily to make your program bloat.

Handling NullPointerException

In the above case, even if we pass null to the method it will throw a much more meaningful exception as mentioned below:

Exception in thread "main" java.lang.IllegalArgumentException: array is null
at HelloWorld.getArrayLength(HelloWorld.java:9)
at HelloWorld.main(HelloWorld.java:5)

There can be many other scenarios around the same concept and the best way to fix the null pointer exception would be to debug your program in an Integrated Development Environment like Eclipse. This way you can easily identify what is causing java.lang.NullPointerException and can fix accordingly. 

Please follow and like us:

Leave a Comment

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

Scroll to Top