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

exception, java, nullpointerexception

Solution

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`.

Problem

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`.

Original source