Reputation: 13118
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.
Upvotes: 5
Views: 1057
Reputation: 2867
Zero length array is still an array, and memory will be allocated to this array.
Array implements Object. Object is a class with methods a fields.
Size is also additional field in memory that indicates the size of array.
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.
Upvotes: 5
Reputation: 9842
Arrays in Java are objects. For instance it has "length" variable. and also the related data. Therefore even if you create a 0 size array only the data part will be zero in size. The other parts of the array object will be still there.
Upvotes: 2
Reputation: 311054
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?
Upvotes: 3