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
.
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:
You hit by the bolder point, since the array is null
.
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 anyindex < 0
orindex > 19
, ArrayIndexOutOfBoundException will be thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With