NullPointerException

NullPointerException


NullPointerException is an unchecked exception from java.lang package. As the name indicates, if an object points to null and further used in the code, the JVM throws NullPointerException.

Following is the class signature

public class NullPointerException extends RuntimeException

Following is the hierarchy

Object –> Throwable –> Exception –> RuntimeException –> NullPointerException

NullPointerException can be thrown by JVM in a number of cases in Java. Three cases are given hereunder.

1. Object not pointing any value

In the following program a button object btn is declared as an instance variable. In the constructor btn is created. In the display() method, a background color is set to button. Then where is the error?

Observe the code.

Button btn = new Button(“OK”);

The btn in the above statement is local to the constructor. It is no way connected to the instance button variable btn. The btn in display() method refers the instance variable btn which not instantiated. Here, btn is just a reference variable that does not point any value. At this juncture, the JVM throws NullPointerException.

2. Using a null object

In the following program, string str is assigned with null. The null object str is compared with hello. The JVM reacts by throwing NullPointerException.

NullPointerException

3. Adding null to DS that does not accept

Some collections classes do not accept null values. For example, Hashtable does not accept null keys and null values. If added as in the following program, the JVM throws NullPointerException.

Observe the following statement.

ht1.put(null, “Sir”);

The key is null and the value is Sir. The null key (or null value is also) is not an eligible element to Hashtable.

It can be used in coding to throw an exception object also as follows.

NullPointerException

Leave a Reply

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