0

I want to set some data in array from objects, here is class A, it cause an NullPointerException. Why? how to solve this? what is the problem with my initializing?

class A {

    int a;

    public void setA(int a) {
        this.a = a;
    }

public class ObjArry {
public static void main(String[] args) {

    A[] ObjectArray = new A[5];

    ObjectArray[0].setA(10); //Exception occurs in this line
    ObjectArray[1].setA(9);
    ObjectArray[2].setA(8);
    ObjectArray[3].setA(7);
    ObjectArray[4].setA(6);
}
F. Knorr
  • 3,045
  • 15
  • 22

2 Answers2

2

An exception will occur on all other lines, too. By default, the newly initialized array new A[5] is empty, i.e., all its fields are null. You first have to do something like:

ObjectArray[0] = new A();
ObjectArray[1] = new A();
ObjectArray[2] = new A();
ObjectArray[3] = new A();
ObjectArray[4] = new A();
F. Knorr
  • 3,045
  • 15
  • 22
1

JLS §10.6 states that

[...] each component of the (newly created1) array is initialized to its default value (§4.12.5).

(1The comment was added by me.)

Looking at §4.12.5, we find that

For all reference types (§4.3), the default value is null.

In consequence,

A[] ObjectArray = new A[5];

creates an array of length 5 and each cell contains a reference to null.

So the answer is: It happens because the JLS says so.

Turing85
  • 18,217
  • 7
  • 33
  • 58