Null Pointer Exception In Java – Explained | How To Avoid and Fix

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. Exception Handling in Java is one of the effective means to handle runtime errors and exceptions so that the normal flow of the application can be maintained. Null Pointer Exceptions in Java occur when a Java program attempts to use an object reference that has a null value. In the Java world, you can assign a null value to an object reference.

What is Null Pointer Exception in Java?

The Null Pointer Exception in Java i.e java.lang.NullPointerException is a kind of Runtime Exception that occurs when the program tries to use an object reference that is set to the null value. Being a Runtime Exception, the NullPointerException in Java is not required to be caught and handled in the application code.

NullPointer Exception Example

Refer to the below code example to understand the NullPointerException. In this example, the equals() method is called without the null check prior to calling the method.

class Test {
  public static void main(String[] args) {
    // Setting null value to the String variable obj
    String obj = null;
    // Using object with null value
    if (obj.equals("text")) // It throws NullPointerException
      System.out.print("Same");
    else
      System.out.print("Not Same");
  }
}

What Causes NullPointer Exception?

The NullPointerException in a Java program occurs when you try to access or modify an uninitialized object. The following are the most common situations for the NullPointerException occurrence.

  1. When null parameters are passed on to a method.
  2. Trying to access the properties or an index element of a null object.
  3. Calling methods on a null object.
  4. Following incorrect configuration for dependency injection frameworks such as Spring.

How to Fix NullPointer Exception?

To fix NullPointerException in Java programming, you should check the variable for empty or null value before it is used any further.

import org.apache.commons.lang3.StringUtils;
class Test {
  public static void main(String[] args) {
    // Setting null value to the obj variable
    String obj = null;
    // Using object with null value
    if (StringUtils.isNotEmpty(obj) && obj.equals("text"))
      System.out.print("Same");
    else
      System.out.print("Not Same");
  }
}

In order to fix the java.lang.NullPointerException, the main() method in the above code is updated with a check using the StringUtils.isNotEmpty() method that checks whether the string object obj is empty or not. If the string object obj is empty or null, it prints the message “Not Same” to the console and if the string object obj is not null and equals “text”, it prints the message “Same”.

How to Avoid the NullPointerException?

To avoid NullPointerException, always make sure that all the objects are properly initialized before you use them. Before invoking a method on an object, verify that the object is not null.

Given below are some NullPointerException problems with solutions.

1. String Comparison With Literals

The most common NullPointerException problems involve a comparison between a variable and a literal that may be a string or an element of Enum. Consider invoking the method from the literal rather than invoking it from the null object. In the below code, NullPointerException is avoided by calling equals() on literal instead of calling object.

// A Java program to demonstrate that 
// we can avoid NullPointerException
import java.io.*;
class GFG {
  public static void main (String[] args) {
    // Initialing String variable with null value
    String ptr = null;
    // Checking if ptr is null using try catch.
    try {
      if ("text".equals(ptr))
        System.out.print("Same");
      else
        System.out.print("Not Same");
    } catch(NullPointerException e) {
      System.out.print("Caught NullPointerException");
    }
  }
}

Output:

Not Same

2. Handle Method Arguments and Returns

Always ensure that the arguments of the new method are non-null before executing the body. Continue with the method execution only after the arguments are properly checked. If any argument is null, it should return an IllegalArgumentException and notify the calling method that something isn’t right with the arguments passed. Similarly, always check method returns for null value before using.

// A Java program to demonstrate that we should check 
// if parameters are null or not before using them.
import java.io.*;
class GFG {
  public static void main (String[] args) {
    // String s set an empty string and calling getLength()
    String s = "";
    try {
      System.out.println(getLength(s));
    } catch(IllegalArgumentException e) {
      System.out.println("IllegalArgumentException caught");
    }
    // String s set to a value and calling getLength()
    s = "GeeksforGeeks";
    try {
      System.out.println(getLength(s));
    } catch(IllegalArgumentException e) {
      System.out.println("IllegalArgumentException caught");
    }
    // Setting s as null and calling getLength()
    s = null;
    try {
      System.out.println(getLength(s));
    } catch(IllegalArgumentException e) {
      System.out.println("IllegalArgumentException caught");
    }
  }
  // Function to return length of string s. It throws
  // IllegalArgumentException if s is null.
  public static int getLength(String s) {
    if (s == null)
      throw new IllegalArgumentException("The argument cannot be null");
    return s.length();
  }
}

Output:
0
13
IllegalArgumentException caught

To avoid NullPointerExceptions, you need to take care that all objects are initialized with a legitimate value (that is not null), before using them. Any operation performed on a null reference variable results in NullPointerException.

Also Read: Exceptions in Java

3. Use Optional (Java 8+)

Consider using Optional to handle cases where a variable might be null. Optional allows you to provide a default value or behavior if the object is null.

import java.util.Optional;
public class OptionalExample {
  public static void main(String[] args) {
    String[] str = new String[10];
    Optional<String> checkNull = Optional.ofNullable(str[5]);
    if(checkNull.isPresent()){ // It Checks, value is present or not
      System.out.print(str[5]);
    } else {
      System.out.println("String value is not present");
    }
  }
}
Output:
String value is not present

4. Objects.requireNonNull

The Objects.requireNonNull method (introduced in Java 7) is a helpful utility to explicitly check for null and throw a NullPointerException with a specified error message if null.

public void someMethod(Object obj) {
Objects.requireNonNull(obj, "Object cannot be null");
  // Rest of the logic
}

5. Avoid Unchecked Casting

Be cautious when using type casting (e.g., (String) someObject). Ensure that the object is of the expected type to avoid potential ClassCastException or NullPointerException.

if (someObject instanceof String) {
  String str = (String) someObject;
  // Use str
} else {
  // Handle other cases
}

6. Use Defensive Programming and Follow Design Patterns

Write defensive code that anticipates potential null values and handles them gracefully. Modern Java frameworks often provide built-in mechanisms or annotations to handle NullPointerException, such as Spring’s @Nullable or JetBrains’ @NotNull. Consider using assertions or explicit error checks. Also, design your code to use appropriate design patterns like the Null Object pattern or the Factory pattern to mitigate null-related issues.

Conclusion

Avoiding and fixing NullPointExceptions is an important task for developers. That’s why developers need additional tools that can help them prevent and fix NullPointerExceptions in Java. Seagence, a Realtime Defect Detection and Resolution tool, detects known and unknown defects in your Java code using a unique approach caused by multithreading issues, swallowed exceptions, caught exceptions, 500 errors, and defects that are disguised as HTTP 200 success codes. It also detects the root cause exception of the defect and automates Java error management, prioritizing the errors, and making the process of error and defect fixing easier than ever reducing MTTR by 90%. Try Seagence free today! Click here to know more.