What is java.lang.NullPointerException in java, when it occurs,how to handle, avoid and fix it


In this exception and exception handling tutorial we will learn what is NullPointerException in java, What is hierarchy of java.lang.NullPointerException, whether NullPointerException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java, Few basic points about NullPointerException in java, When NullPointerException is thrown in java, Scenarios where NullPointerException is thrown in java, how to avoid/ Handle NullPointerException thrown in java, example where NullPointerException thrown using multi-threading/ threads in java.


Contents of page >
  • What is hierarchy of java.lang.NullPointerException?

  • NullPointerException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java ?

  • What is NullPointerException in java?

  • Few basic points about NullPointerException in java
  • When NullPointerException is thrown in java?

  • Now let’s discuss above points in detail - Scenarios where NullPointerException is thrown in java

  • Avoid/ Handle NullPointerException thrown in java

  • Another example where NullPointerException thrown using multi-threading/ threads in java


What is hierarchy of java.lang.NullPointerException?

-java.lang.Object
-java.lang.Throwable
 -java.lang.Exception
  -java.lang.RuntimeException
   -java.lang.NullPointerException

NullPointerException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java ?

java.lang.NullPointerException is a RuntimeExceptions in java.


What is NullPointerException in java?

NullPointerException is thrown when an java application tries to use null in place of object.

It happens generally when something has not been initialized properly.
Before moving further I’ll like to take very very small example >
   String str =null;
   str.charAt(0); //It will throw NullPointerException
str is reference variable of String type, but currently str is pointing to NULL (nothing), so calling charAt method on nothing will throw NullPointerException.

Few basic points about NullPointerException in java >
  1. NullPointerException is that which need to be taken care of at runtime not at compile time.
  2. Whenever NullPointerException occurs execution of program is interrupted, but by handling these NullPointerException properly we can avoid such interruptions.
  3. NullPointerException is automatically propagated in java.
  4. If superclass method throws/declare NullPointerException >
  • overridden method of subclass can declare/throw NullPointerException or any RuntimeException (As shown in Program), or
  • overridden method of subclass cannot declare/throw any checked exception (As shown in Program),

When NullPointerException is thrown in java?

  1. NullPointerException is thrown in java when an instance method of a null object is accessed.
  2. Any attempt to access or modify the field of a null object throws NullPointerException in java.
  3. Finding out length of null array throws NullPointerException .
  4. Accessing or modifying the slots of null array throws NullPointerException in java.
  5. Throwing null as if it were a Throwable value throws NullPointerException in java.

NullPointerException  in Collection framework classes (in java.util.Set).
  1. TreeSet doesn’t allows to store null elements. Any attempt to store null elements will throw NullPointerException.
  2. ConcurrentSkipListSet doesn’t allows to store null elements. Any attempt to store null elements will throw NullPointerException.

NullPointerException  in Collection framework classes (in java.util.Map).
  1. Hashtable doesn’t allows to store null keys or null values. Any attempt to store null keys or null values will throw NullPointerException.
  2. ConcurrentHashMap doesn’t allows to store null keys or null values. Any attempt to store null keys or null values will throw NullPointerException.
  3. TreeMap doesn’t allows to store null keys. Any attempt to store null keys will throw NullPointerException.
  4. ConcurrentSkipListMap doesn’t allows to store null keys or null values. Any attempt to store null keys or null values will throw NullPointerException.

Note : NullPointerException  in Collection framework classes (in java.util.List).
Almost all the common implementations of List like ArrayList, LinkedList, Vector, CopyOnWriteArrayList allows to store null.

Now let’s discuss above points in detail - Scenarios where NullPointerException is thrown in java>


  1. NullPointerException is thrown when an instance method of a null object is accessed.

In below program Employee object is null and NullPointerException is thrown when an instance method getId() of a null Employee object is accessed.
class Employee{
int id;
public int getId() {
     return id;
}
}
public class NullPointerExceptionExample1 {
public static void main(String args[]) {
     Employee emp =null;
     emp.getId();   //It will throw NullPointerException
}
}
/*OUTPUT
Exception in thread "main" java.lang.NullPointerException
at  NullPointerExceptionExample1.main(NullPointerExceptionExample1.java:11)

*/

Likewise, String is an object, in below program String object is null and NullPointerException is thrown when an instance method charAt() of a null String object is accessed.
public class NullPointerExceptionAccessStringExample {
public static void main(String args[]) {
     String str =null;
     str.charAt(0);      //It will throw NullPointerException
}
}
/*OUTPUT
Exception in thread "main" java.lang.NullPointerException
at  NullPointerExceptionAccessStringExample.main(NullPointerExceptionAccessStringExample.java:4)
*/

  1. Any attempt to access or modify the field of a null object throws NullPointerException.
class Employee{
int id;
public int getId() {
     return id;
}
}
public class NullPointerExceptionExample2 {
public static void main(String args[]) {
     Employee emp =null;
     emp.id= 1;     //It will throw NullPointerException
}
}
/*OUTPUT
Exception in thread "main" java.lang.NullPointerException
at  NullPointerExceptionExample2.main(NullPointerExceptionExample2.java:11)

*/

  1. Finding out length of null array throws NullPointerException .
public class NullPointerExceptionExample3 {
public static void main(String args[]) {
     int arr[] = null;
     System.out.println(arr.length); //It will throw NullPointerException
}
}
/*OUTPUT
Exception in thread "main" java.lang.NullPointerException
at  NullPointerExceptionExample3.main(NullPointerExceptionExample3.java:4)
*/

  1. Accessing or modifying the slots of null array throws NullPointerException.
public class NullPointerExceptionExample4 {
public static void main(String args[]) {
     int arr[] = null;
     arr[0]=1; //It will throw NullPointerException
}
}
/*OUTPUT
Exception in thread "main" java.lang.NullPointerException
at NullPointerExceptionExample4.main(NullPointerExceptionExample4.java:4)
*/

  1. Throwing null as if it were a Throwable value throws NullPointerException .
public class NullPointerExceptionExample5 {
public static void main(String args[]) {
     m();
}
static void m(){
     throw null; //It will throw NullPointerException
}
}
/*OUTPUT
Exception in thread "main" java.lang.NullPointerException
at NullPointerExceptionExample5.m(NullPointerExceptionExample5.java:6)
at NullPointerExceptionExample5.main(NullPointerExceptionExample5.java:3)
*/



How to avoid Avoid/ Handle NullPointerException thrown in java>


  1. if condition check
Check whether String is null or not using if condition.
public class NullPointerExceptionAvoidExample1 {
public static void main(String args[]) {
     String str =null;
     if(str!=null){ //perform operation only when string is NOT null
          System.out.println("str is NOT null");
          //.....
     }
     else{
          System.out.println("str is null");
     }
}
}
/*OUTPUT
str is null
*/

  1. Using instanceOf
Use instanceof to find whether str is null or it’s actually an instance of String.
public class NullPointerExceptionAvoidExample2_instanceOf {
public static void main(String args[]) {
     String str =null;
     if(str instanceof String){  //It won't throw NullPointerException
          //.....
     }
     else{
          System.out.println("str is not instanceof String");
     }
}
}
/*output
str is not instanceof String
*/

  1. How to use equals method
As we discussed above in (Scenarios where NullPointerException may be thrown in java - 1st point) - NullPointerException is thrown when an instance method of a null object is accessed.

String is an object, in below program String object is null and NullPointerException is thrown when an instance method equals() of a null String object is accessed.
public class NullPointerExceptionAvoidExample3_ {
public static void main(String args[]) {
     String str =null;
     if(str.equals("abc")){  //It will throw NullPointerException
          //.....
     }
}
}
/*OUTPUT
Exception in thread "main" java.lang.NullPointerException
at  NullPointerExceptionAvoidExample3_.main(NullPointerExceptionAvoidExample3_.java:4)
*/

In below program, String literal "abc" is not a null object.
So, calling equals method on "abc" will never throw  NullPointerException.

public class NullPointerExceptionAvoidExample3 {
public static void main(String args[]) {
     String str =null;
     if("abc".equals(str)){   //It won't throw NullPointerException
          //.....
     }
     else{
          System.out.println("NOT EQUAL");
     }
}
}
/*OUTPUT
NOT EQUAL
*/

Internally, equals method will check for instanceof.
Inside equals method following statement will be executed   
public boolean equals(Object obj) {
       //..
      if(obj instanceof String)//false, because (null instanceof String) will return false
        //..                   //execution will never enter if loop
    }
      return false; //and ultimately equals method will return false.
}

  1. Check arguments passed are null or not
If argument passed is null, Return from method without doing any operation.
public class NullPointerExceptionAvoidExample4 {
public static void main(String args[]) {
     String str = null;
     m(str);
}
static void m(String str) {
     if (str != null) { // perform operation only when string is NOT null
          System.out.println("str is NOT null");
          // .....Do your stuff
     } else {
          System.out.println("str is null, returning without doing anything");
          return;
     }
}
}
/*OUTPUT
str is null, returning without doing anything
*/

  1. Using ternary conditions can be very handy in handling NullPointerException
public class NullPointerExceptionAvoidExample5_ternary {
public static void main(String args[]) {
     String str =null;
     System.out.println(str != null ?  "str is NOT null" : "str is null");
}
}
/*OUTPUT
str is null
*/

  1. Using org.apache.commons.lang.StringUtils is very good option to avoid NullPointerException in java, methods of this class will never throw NullPointerException
import org.apache.commons.lang.StringUtils;
public class NullPointerExceptionAvoidExample6_StringUtils {
public static void main(String[] args) {
     String   str=null;
     StringUtils.isEmpty(str); //true
     StringUtils.isBlank(str); //true
    
     StringUtils.isNotEmpty(str); //false
     StringUtils.isNotBlank(str); //false
    
}
}

  1. using primitive data types in place of Object wrapper class
When it comes to numeric data types, using primitive data types in place of Object wrapper class can be used to avoid NullPointerException in java.

Example -
static Member variable of class Integer i will be initialized to null.
public class NullPointerExceptionAvoidExample7__Integer {
static Integer i;
public static void main(String[] args) {
     System.out.println(i+1); //It will throw NullPointerException
}
}
/*OUTPUT
Exception in thread "main" java.lang.NullPointerException
at NullPointerExceptionAvoidExample7__Integer.main(NullPointerExceptionAvoidExample7__Integer.java:4)
*/

But, static Member variable of class int i will be initialized to 0 rather than null and we can easily avoid NullPointerException in java.

public class NullPointerExceptionAvoidExample7_int {
static int i;
public static void main(String[] args) {
     System.out.println(i+1); //1
}
}
/*OUTPUT
1
*/

Read  this article to know more about when to use When to use primitive type and wrapper classes?

  1. Always return Collections.emptyList() in place of return null list.
Example program to show Returning null list is can further throw NullPointerException.
import java.util.List;
public class NullPointerExceptionAvoidExample8__collection {
   private static List<Integer> list = null;
   public static void main(String[] args) {
     System.out.println(m().toString()); //It will throw NullPointerException

}
   public static List<Integer> m() {
         //Your Logic...
     return list;
  }
}
/*OUTPUT
Exception in thread "main" java.lang.NullPointerException
at  NullPointerExceptionAvoidExample8__collection.main(NullPointerExceptionAvoidExample8__collection.java:6)
*/

As a precaution we must return Collections.emptyList(), it will never throw NullPointerException.
import java.util.Collections;
import java.util.List;
public class NullPointerExceptionAvoidExample8_collection {
   private static List<Integer> list = null;
   public static void main(String[] args) {
     System.out.println(m().toString());
}
   public static List<Integer> m() {
     if (list == null){
        return Collections.emptyList(); //It will return new EmptyList<>();       
     }
     else{
        //Your Logic...
          return list;
     }
   }
}
/*OUTPUT
[]
*/

  1. use String.valueOf() - Never throw NullPointerException .
in place of
toString() - Can throw NullPointerException .

About toString()  >
As we discussed above in (Scenarios where NullPointerException may be thrown in java - 1st point) - NullPointerException is thrown when an instance method of a null object is accessed.

String is an object, in below program String object is null and NullPointerException is thrown when an instance method toString() of a null String object is accessed.
public class NullPointerExceptionAvoidExample9_toString {
   public static void main(String[] args) {
          String str = null;
          System.out.println(str.toString()); //It will throw NullPointerException
         
   }
}
/*OUTPUT
Exception in thread "main" java.lang.NullPointerException
   at NullPointerExceptionAvoidExample9_toString.main(NullPointerExceptionAvoidExample9_toString.java:4)
*/

About String.valueOf()  >

public class NullPointerExceptionAvoidExample9_valueOF {
   public static void main(String[] args) {
          String str = null;
          System.out.println(String.valueOf(str)); //null
   }
}
/*OUTPUT
null
*/
Above program will print "null" string.
null is not a string, it’s nothing, but "null" is a string.

Internally, valueOf method will check for (obj==null).
Inside valueOf  method following statement will be executed   
public static String valueOf(Object obj) {
return (obj==null) ? "null" : obj.toString(); //return "null", because (null == null) will return true
}


  1. We can make member variables or methods as static to avoid NullPointerException, but we careful about usage or static keyword in java.

Static variables. -We need not to create instance of class for accessing static variables.
class Employee{
   int id = 1;
   static String company="XYZ";  
}
public class StaticVariableTest {
   public static void main(String[] args) {
          Employee emp= null;
         
          //System.out.println(emp.id) ;  //It will throw NullPointerException
          System.out.println(emp.company);
   }
}

/*OUTPUT
XYZ
*/
Static variables can be accessed directly using class name as well System.out.println(Employee.company);

Static methods - We need not to create instance of class for accessing static methods.
class Emp{
   void method(){
          System.out.println("instance method");
   }
   static void staticMethod(){
          System.out.println("static method");
   }
}
public class StaticMethodTest {
  
   public static void main(String[] args) {
          Emp emp = null;
          //emp.method();  //It will throw NullPointerException
          emp.staticMethod();
   }
         
}
/*OUTPUT
static method
*/
Static methods can be accessed directly using class name as well Employee.staticMethod;


  1. Avoid NullPointerException  in Collection framework classes (in Set).

Though TreeSet, ConcurrentSkipListSet  doesn’t allows to store null elements. But, other implementations of Set like HashSet, CopyOnWriteArraySet, LinkedHashSet allows to store null.

  1. Avoid NullPointerException  in Collection framework classes (in Map).

Hashtable, ConcurrentHashMap, ConcurrentSkipListMap doesn’t allows to store.
doesn’t allows to store null keys or null values.
TreeMap doesn’t allows to store null keys.

But HashMap, LinkedHashMap allows one null key and many null values.

  1. Writing unit test cases is important to avoid NullPointerException, you may write Junit or Mockito for writing test cases.

  1. use containsKey  and containsValue method to avoid NullPointerException,

If map does not contains key, hashMap.get(7) will return null, it is NullPointerException prone in java.
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String args[]){
   Map<Integer,String> hashMap=new HashMap<Integer,String>();
   hashMap.put(11, "ankit");
   hashMap.put(21, "mittal");
   System.out.println(hashMap.get(7));
}
}
/*OUTPUT
null
*/

But, using containsKey  and containsValue method reduces risk of NullPointerException.
import java.util.HashMap;
import java.util.Map;
public class HashMapTest {
public static void main(String args[]){
  
   Map<Integer,String> hashMap=new HashMap<Integer,String>();
   hashMap.put(11, "ankit");
   hashMap.put(21, "mittal");
   System.out.println("\n----- containsKey method returns true if map "
                 + "contains a mapping for the specified key ---");
   if(hashMap.containsKey(7)){
          System.out.println(hashMap.get(7));
   }
   else{
          System.out.println("hashMap does not contain specified key");
   }
  
   System.out.println("\n----- containsValue method returns true if one or "
                 + "more keys in map contains specified value ---");
   if(hashMap.containsValue("kat")){
          System.out.println("hashMap contain specified value");
   }
   else{
          System.out.println("hashMap does not contain specified value");
   }
  
  
}
}
/*OUTPUT
----- containsKey method returns true if map contains a mapping for the specified key ---
hashMap does not contain specified key
----- containsValue method returns true if one or more keys in map contains specified value ---
hashMap does not contain specified value
*/

  1. Use Null Object Design Pattern to avoid NullPointerException in Java

  1. Using Assertions in java
Generally during testing phase we use assert keyword to avoid NullPointerExceptions in java.

Before executing below you must pass -ea as JVM argument, otherwise assertions will be ignored and line below it will throw NullPointerException at runtime.
public class NullPointerExceptionAvoidExample10_assertions {
   public static void main(String args[]) {
          String str = null;
          assert (str != null);
          System.out.println(str.charAt(0));
   }
}
/*OUTPUT
Exception in thread "main" java.lang.AssertionError
   At NullPointerExceptionAvoidExample10_assertions.main(NullPointerExceptionAvoidExample10_assertions.java:4)
*/

Another example where NullPointerException thrown using multi-threading/ threads in java>

package o13_k15;
class Class2 {
   void method2(String name) {
          for (int x = 1; x <=2; x++) {
                 System.out.println(Thread.currentThread().getName());
          }
   }
}
public class MyClass implements Runnable {
   Class2 obj2;
   public static void main(String[] args) {
          new MyClass().method1();
   }
   void method1() {
          obj2 = new Class2();
          new Thread(new MyClass()).start();
          new Thread(new MyClass()).start();
   }
   public void run() {
          obj2.method2(Thread.currentThread().getName());
   }
}

Answer.  Program will throw NullPointerException at Class2 obj2, we must make it static. As new Thread(new MyClass()).start(); creates thread on new instance of MyClass.

Solution to avoid NullPointerException in above multi-threading program>
If Class2 obj2 is made static, than
Thread-0 and Thread-1 will be printed twice but in unpredictable order.

So, output may be different in subsequent executions because behaviour of thread scheduler is unpredictable (as shown below)-

/*OUTPUT
Thread-1
Thread-1
Thread-0
Thread-0
*/
/*OUTPUT
Thread-0
Thread-1
Thread-1
Thread-0
*/

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

So in this exception and exception handling tutorial we learned what is NullPointerException in java, What is hierarchy of java.lang.NullPointerException, whether NullPointerException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java, Few basic points about NullPointerException in java, When NullPointerException is thrown in java, Scenarios where NullPointerException is thrown in java, avoiding/ Handle NullPointerException thrown in java, example where NullPointerException thrown in multi-threading/ threads in java.

.

RELATED LINKS>

Collection - List, Set and Map all properties in tabular form

NumberFormatException in java
OutOfMemoryError in java

SQLException in java

IndexOutOfBoundsException in java

Solve java.lang.UnsupportedOperationException in java


No comments:

Post a Comment