0 votes
1 view
in Java by (10.2k points)

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.

1 Answer

0 votes
by (46.1k points)

This is correct.

A[] a = new A[4];

creates 4 A references, similar to doing this

A a1;

A a2;

A a3;

A a4;

now you couldn't do a1.someMethod() without allocating a1 as

a1 = new A();

similarly, with the array you need to do

a[0] = new A();

before using it.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 11 in Java by Krishna (2.6k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...