Reasons and Solutions of Null Pointer Exception in Java

In this article, we will learn about null pointer exceptions in Java and look into some of the common errors that result in them. We will also see how we can prevent them from happening.

What is a Null Pointer Exception in Java?

The Null Pointer Exception is a runtime exception in Java. It is also called the unchecked exception as it escapes during compile-time but is thrown during runtime. A program throws this exception when it attempts to dereference an object that has a null reference.

Simply put, the null pointer exception is raised when we try to call a method or variable that has a null reference.

Let’s see an example,

class example{
  static String word = null;
  public static void main(String args[]){
    word = word.toUpperCase();
  }
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke
"String.toUpperCase()" because "example.word" is null at example.main(example.java:4)

From the above code, we see that when we call the String variable word to change to the upper case, we get a null pointer exception as word has a null reference.

Reasons for Null Pointer Exceptions

Some of the common mistakes that we may commit are:

  1. Invoking methods of a null object

    // Invoking methods of a null object
    class example1{
      void add(){
        int x = 4, y = 6;
        System.out.println(x+y); 
      }
      public static void main(String args[]){
        example1 obj = null;
        obj.add();
      }
    }
    Exception in thread "main" java.lang.NullPointerException: Cannot invoke "example1.add()"
    because "<local1>" is null at example1.main(example1.java:9)

    In line 9, we invoked the method add() of an object obj of class example1. Now, obj has a null reference, therefore we got a null pointer exception.

  2. Using or altering fields of a null object.

    // Using or altering fields of a null object
    class example2{
      int x = 10;
      public static void main(String args[]){
        example2 obj = null;
        int i = obj.x; // Accessing the field of a null object 
        obj.x = 20; // Modifying the field of a null object
      }
    }
    Exception in thread "main" java.lang.NullPointerException: Cannot read 
    field "x" because "<local1>" is null at example2.main(example2.java:6)

    Similar to example1, when the object obj of class example2 itself has a null reference then it is not possible to either access or modify its fields. The program threw a null pointer exception due to line 6.

  3. Calling length of a null array.

    // Calling length of a null array
    import java.util.*;
    class example3{
      public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int arr[] = null;
        System.out.println(arr.length);
      }
    }
    
    Exception in thread "main" java.lang.NullPointerException: Cannot read the
    array length because "<local2>" is null at example3.main(example3.java:7)

    We created an integer array arr, but we assigned it to null which means that there is no information to store. Therefore, we got the null pointer exception when we tried to access the length of the null array.

  4. Using or altering the items of a null array.

    // Using or altering the items of a null array
    class example4{
      public static void main(String args[]){
        int arr[] = null;
        arr[2]=arr[3]+2;
      }
    }
    Exception in thread "main" java.lang.NullPointerException: Cannot load
    from int array because "<local2>" is null at example4.main(example4.java:7)

    Similar to example3, when there is no information in the array it is not possible to access or modify the elements that do not even exist. Therefore, a null pointer exception was thrown due to line 7.

  5. Throwing null value instead of a valid object.

    // Throwing null value instead of a valid object
    class example5{
      public static void main(String args[]){
        throw null;
      }
    }
    Exception in thread "main" java.lang.NullPointerException: Cannot throw exception
    because "null" is null at example5.main(example5.java:4)

    In this example, we tried to throw a null value instead of a valid object. Therefore, the null pointer exception was thrown.

Avoiding Null Pointer Exceptions

Let’s discuss some situations where we can carry out some steps to prevent null pointer exceptions. Of course, we must take care of all the above-mentioned reasons.

  1. Inspect the arguments passed to a method
    Sometimes, we may pass variables with null values to a method that results in a null pointer exception during runtime. It is always a better practice to check the arguments before proceeding to use them in the method.
    Let’s look at an example,

    class example_1{
      static int add(String s){
        try{
          System.out.println(s.concat("HI"));
        }catch(NullPointerException e){
          System.out.println("null value found");
        }
        return 6;
      }
      public static void main(String args[]){
        String word = null;
        System.out.println(add(word));
      }
    }
    null value found
    6

    s is assigned a null value. Since we checked on it before continuing, using a try-catch block, we did not encounter a null pointer exception.

  2. Use of ternary operators
    class example_2{  
    public static void main(String[] args){
      String word = null; 
      String output = (word == null) ? "null value" : word.toUpperCase();  
      System.out.println(output);  
      
      word = "code speedy";  
      output = (word == null) ? "null value" : word.toUpperCase();  
      System.out.println(output);  
      }  
    }
    null value
    CODE SPEEDY

    In line 4, we used the ternary operator to check if word is null. Since it is null, output will be “null value”. If we had not used the ternary operator then the program would have thrown the exception.

  3. To prefer valueOf() over toString()
    When we use toString() on a null object then the program throws the null pointer exception. Instead, we can get the same value by calling valueOf(). When the object passed has a null reference then valueOf() will return “null”, preventing the exception.
    For example,

    class example_3{
      public static void main(String args[]){
        String word = null;
        System.out.println("Using valueOf():\n"+ String.valueOf(word)); // returns null
        System.out.println("Using toString():");
        System.out.println(word.toString()); // throws null pointer exception
      }
    }
    Using valueOf():
    null
    Using toString():
    Exception in thread "main" java.lang.NullPointerException: Cannot invoke
    "String.toString()" because "<local1>" is null at example_4.main(example_4.java:6)
  4. Another way to prevent null pointer exceptions is to prefer using primitive data types over the wrapper classes like Integer, Float, Double and BigDecimal.

I hope this article has helped you understand the null pointer exceptions in Java.

Also read: Java Exceptions , Errors , Exception Handling in Java

Leave a Reply

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