ArrayList NullPointerException

Java's ArrayList is a great Collection that frees us from IndexOutOfBound, one type limitation, and NullPointerException issues while providing several value-added methods. Naturally, you would be shocked if you encounter a NullPointerException on an ArrayList. The only time, you would encounter this problem is when you fail to initialize the ArrayList.

import java.util.ArrayList;

public class ArrayListNullExample
{
   ArrayList a;

   public ArrayListNullExample() {}

   public int getSize() {
       return a.size();
   }

   public static void main(String[] args) {
       ArrayListNullExample a = new ArrayListNullExample();
       System.out.println(a.getSize());
   }
}

This program outputs nothing and throws a NullPointerException at return a.size. To solve this problem, simply initialize as follows and the output should be 0.

import java.util.ArrayList;

public class ArrayListNullExample
{
   ArrayList a = new ArrayList();

   public ArrayListNullExample() {}

   public int getSize() {
       return a.size();
   }

   public static void main(String[] args) {
       ArrayListNullExample a = new ArrayListNullExample();
       System.out.println(a.getSize());
   }
}
Technologies: