English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

When does a Java array throw a NullPointerException exception?

In Java, each type has a default value, and when you do not initialize the instance variables of a class, the Java compiler will use these values to initialize them for you. Null is the default value for the object type, and you can also manually assign null to an object in a method.

Object obj = null;

However, you cannot use an object with a null value or (if you use a null value instead of an object) an object, which will cause a NullPointerException.

Example

public class Demo {
   String name = "Krishna";
   int age = 25;
   public static void main(String args[]) {
      Demo obj = null;
      System.out.println(obj.age);
      System.out.println(obj.name);
   }
}

Runtime Exception

Exception in thread "main" java.lang.NullPointerException
   at july_set3.Demo.main(Demo.java:11)

According to the Java documentation, if you try to execute NullPointerException-

  • Call method a of a null object (instance).

  • Access, modify, print the fields of a null value (object).

  • Attempt to access (print/Use the length of a null value in a statement.

  • throw a null value.

  • Access or modify an element with a null value/slot.

is thrown if it is an array.

In Java arrays, reference types are like classes, so the scenarios where NullPointerException occurs are almost similar. When using arrays, NullPointerException-

  • If you try to access an element of an uninitialized array (null).

public class Demo {
   public static void main(String args[]) {
      int myArray[] = null;
      System.out.println(myArray[5]);
   }
}

Runtime Exception

Exception in thread "main" java.lang.NullPointerException
   at july_set3.Demo.main(Demo.java:6)
  • If you try to get the length of an uninitialized array (null).

public class Demo {
   public static void main(String args[]) {
      int myArray[] = null;
      System.out.println(myArray.length);
   }
}

Runtime Exception

Exception in thread "main" java.lang.NullPointerException
   at july_set3.Demo.main(Demo.java:6)
  • If you try to call any method on an uninitialized array (null).

public class Demo {
   public static void main(String args[]) {
      int myArray[] = null;
      System.out.println(myArray.toString());
   }
}

Runtime Exception

Exception in thread "main" java.lang.NullPointerException
   at july_set3.Demo.main(Demo.java:6)