Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ExceptionInInitializerError Caused by: java.lang.NullPointerException

This is from OCJP example. I have written a following code

public class Test {

  static int x[];

  static {
     x[0] = 1;
  }

  public static void main(String... args) {
  }        
}       

Output: java.lang.ExceptionInInitializerError

Caused by: java.lang.NullPointerException at x[0] = 1;

Why it is throwing NullPointerException and not ArrayIndexOutOfBoundException.

like image 456
Prashant Shilimkar Avatar asked Dec 09 '13 09:12

Prashant Shilimkar


2 Answers

Why it is throwing NullPointerException and not ArrayIndexOutOfBoundException.

Because you did not initialize the array.

Initialize array

   static int x[] = new int[10];

Reason for NullPointerException:

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

You hit by the bolder point, since the array is null.

like image 150
Suresh Atta Avatar answered Sep 18 '22 12:09

Suresh Atta


It's throwing NullPointerException because x is null.

x[] is declared, but not initialized.
Before initialization, objects have null value, and primitives have default values (e.g. 0, false etc)

So you should initialize as shown below:

static int x[] = new int[20]; //at the time of declaration of x
or
static int x[];
x = new int[20]; //after declaring x[] and before using x[] in your code

ArrayIndexOutOfBoundException will occur if array is initialized and accessed with an illegal index.

e.g :
x contains 20 elements, so index numbers 0 to 19 are valid, if we access with any index < 0 or
index > 19, ArrayIndexOutOfBoundException will be thrown.

like image 20
Infinite Recursion Avatar answered Sep 19 '22 12:09

Infinite Recursion