When does a Java Array Throws a NullPointerException?


In Java there is default value for every type, when you don’t initialize the instance variables of a class Java compiler initializes them on your be-half with these values. Null is the default value of the object type, you can also manually assign null to objects in a method.

Object obj = null;

But, you cannot use an object with null value or (a null value instead of an object) if you do so, a NullPointerException will be thrown.

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);
   }
}

Run time exception

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

According to Java documentation a NullPointerException occurs if you try to −

  • Call the a method (instance) using null object.
  • Access, modify, print, field of a null value (object).
  • Trying to access (print/use in statements) the length of null value.
  • Throw a null value.
  • Accessing or modifying elements/slots of a null value.

NullPointerException incase of arrays

In Java arrays are reference types just like classes, therefore, the scenarios where NullPointerException occurs are almost similar. While working with arrays a NullPointerException occurs −

  • If you try to access the elements of an array which is not initialized yet (which is 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 array which is not initialized yet (which is 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 invoke any methods on an array which is not initialized yet (which is 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)

Updated on: 02-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements