Shailesh Tainwala
Shailesh Tainwala

Reputation: 6507

In Java, defining an array allocates space for references or for the objects themselves?

In the following line of code, does the compiler allocate memory to store 10 objects of MyClass or 10 references?

MyClass[] arr= new MyClass[10];

In other words, do arrays store references alone or the objects themselves?

Also, is the behaviour different for primitive types?

Upvotes: 4

Views: 2225

Answers (2)

NPE
NPE

Reputation: 500963

When created like this, arrays are automatically initialized with the default value of their type, so arr gets initialized with 10 null references.

Upvotes: 5

Marcelo
Marcelo

Reputation: 11308

It allocates space for the references. In case of primitive types it allocates space = array length * primitive type byte size.

Upvotes: 5

Related Questions