NullPointer Exception in JAVA [Causes and Solution Explained]

JAVA NullPointer Exception

NullPointer Exception is an exception thrown when your code tries to access a memory location containing a null value. This can happen when you declare an object but do not define it. 

In this article we will guide you how to highlight duplicates in a quick and easy way.

WHAT IS A NULLPOINTER EXCEPTION?

Whenever an object that has no memory allocated to it, is called, it will throw an exception. Here, the type of exception is a NullPointer Exception as the object being called is pointing to a null value. Even though JAVA lets you create a null object, it does not let you use it.  Therefore, if you try to access such an object’s methods or attributes, as defined in its class, a NullPointer Exception will be thrown at Runtime.

DECLARE VS. DEFINE

In C language, declaration and definition take place at the same time. However, in JAVA language, both take place separately, one after the other.

Declare

Declaring a variable or object means identifying its attributes, such as the type, name, any initial values etc.

Define

Defining is to allocate a memory location and any implementation to a variable or object after it has been declared.

WHY DOES NULLPOINTER EXCEPTION OCCUR?

Whenever you code, you might declare some objects and use them but forget to actually define them. Since such an object does not have any space allocated to it, it is just like a ghost – it exists, but you cannot touch it.

Hence, any variables or functions that the class may possess, such an object is useless as it cannot access any of those properties. When you compile the code, the compiler is unable to find the reference of the object since it is not stored anywhere. Thus, it will throw this Runtime Exception.

HOW TO FIX IT?

The obvious fix is to define every object as soon as it is declared. However, it is always better to handle exceptions. It is quite possible that the user might enter null values as a parameter which may result in a NullPointer Exception. The try-catch blocks and if-else conditions are great to handle any sort of exceptions thrown without crashing your program.


Handling NullPointer Exception using a Try-Catch Block


Handling NullPointer Exception using an If-Else Condition Block

In case, the whole function does not depend on the parameter and some part of it has to run anyway, then for a NullPointer Exception, use an if-else block at the start to check if the parameter object is null, if so define it with a dummy or invalid value. Any part of the function depending on the parameter object can be executed with a value check or put in the else block.

Tags:JAVA

Leave a Reply