When you allocate an array of objects, each component of the array is initialized to null. The individual components of the array must still be initialized with a constructor or an assignment statement. For example, consider this statement:

Integer[] scores = new Integer[10];
int m = scores[5].intValue(); // throws NullPointerException

This creates an array called scores containing ten references to Integer objects. Then it tries to get the value of the fifth component. However, each of those references is initially set to null. Thus when you try to call a method on one of the components of the array or pass the component to a method that expects a non-null argument, a NullPointerException is thrown.

To fix this, you need to initialize the components of the array, either with constructors or with assignment statements For example:

Integer[] scores = new Integer[10];
for (int i = 0; i < scores.length; i++) scores[i] = new Integer(i);
int m = scores[5].intValue(); 

You do not need to initialize all the components of the array though it's a good idea to do so. You can initialize just those you'll use, or you can make sure you catch and handle NullPointerExceptions in the appropriate places.

This is different from how Java handles uninitialized non-array reference variables. By way of contrast when you write,

Integer score;
int m = score.intValue();

the compiler catches the null reference in score and complains. You have to fix the problem before you can compile the program. However in general the compiler has no way to know whether an array component has or has not been initialized. Therefore the check for the non-nullness of an array component is deferred till runtime when the NullPointerException may be thrown.

Posted in: Java

Related FAQ's

Marius Ion ANGEL HOT SOFT LLC (800) 316-7677