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?

import java.awt.*;
public class NPE
{
  Button btn;
  public NPE()
  {
    Button btn = new Button("OK");
  }
  public void display()
  {
    btn.setForeground(Color.cyan);
  }
  public static void main(String args[]) 
  {  
    new NPE().display();
  }
}

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.

public class NPE
{
  public static void main(String args[]) 
  {  
    String str = null;
    System.out.println(str.equals("hello"));
  }
}

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.

import java.util.Hashtable;
public class NPE
{
  public static void main(String args[]) 
  {  
    Hashtable ht1 = new Hashtable();
    ht1.put(null, "Sir");
  }
}

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.

public class Demo
{
  public static void main(String args[])
  {
      String str = null;
      if(str == null)
      {
           throw new NullPointerException("Object points to null");
      }
  }
}

NullPointerException

Leave a Comment

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