Creating an array of objects in Java

I am new to Java and for the time created an array of objects in Java.

I have a class A for example –

A[] arr = new A[4];

But this is only creating pointers (references) to A and not 4 objects. Is this correct? I see that when I try to access functions/variables in the objects created I get a null pointer exception.
To be able to manipulate/access the objects I had to do this:

A[] arr = new A[4];
for (int i = 0; i < 4; i++) {
    arr[i] = new A();
}

Is this correct or am I doing something wrong? If this is correct its really odd.

EDIT: I find this odd because in C++ you just say new A[4] and it creates the four objects.

9 Answers
9

Leave a Comment