Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array composed of 0 elements. (Java)

Tags:

java

I am studying for the OCA Programmer I Oracle Certification and hence I am reviewing all the tricky things tht might be on the exam. One is this one:

int [] zero = new int[0];

Such an array declared as having 0 in the constructor what is going to actually do in the heap? creating a reference to what? I have already tried to see whether it gives null or not and it does not. (zero != null) passes the test.

Do you have any idea? Thanks in advance.

like image 979
Rollerball Avatar asked Jan 15 '23 07:01

Rollerball


2 Answers

Zero length array is still an array, and memory will be allocated to this array.

  1. Array implements Object. Object is a class with methods a fields.

  2. Size is also additional field in memory that indicates the size of array.

  3. Additional info for tracing the reference to the object by the garbage collection is also needed.

As a result memory allocation is needed for all of this.

More interesting question when this array can be usefull, read this stackoverflow question.

like image 194
Michael Avatar answered Jan 25 '23 02:01

Michael


what is going to actually do in the heap?

A zero-length int array.

creating a reference to what?

A reference to the zero-length int array.

I have already tried to see whether it gives null or not and it does not

Why should it?

like image 35
user207421 Avatar answered Jan 25 '23 00:01

user207421