Below code
public class Example {
static int[] member;
public static void main(String[] args) {
int[] ic = new int[0];
if (ic == null){
System.out.println("ic is null");
}
System.out.println(ic); // [I@659e0bfd
if(member == null){
System.out.println("member is null");
}
}
}
It is obvious that elements can't be added in zero length array.
What does ic
point to, if ic
is not null
?
As per below diagram, Is ic
pointing to memory location 659e0bfd
(which is empty)?
A zero length array is still an instance of Object which holds zero elements.
Although the size of a zero-length array is zero, an array member of this kind may increase the size of the enclosing type as a result of tail padding. The offset of a zero-length array member from the beginning of the enclosing structure is the same as the offset of an array with one or more elements of the same type.
Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.
Zero-length arrays, also known as flexible arrays, are used to implement variable-length arrays, primarily in structures. That's a little confusing, so let's look at an example. Say you wanted a structure to represent an email: Yes, we're missing a lot of fields. This is just an example; bear with me.
What does ic point to, if it is not null?
It points an empty array of zero capacity. Arrays are reference types and memory space is allocated for them like any other reference type.
Imagine an array as a box. You can declare a box with some capacity, say 3
int[] x = new int[3];
and you'll get this box: [_,_,_]
. You can fill it with some numbers
x[1] = 9;
to get [_,9,_]
. What you did, instead, is declaring an zero capacity box
int[] x = new int[0];
to get this: []
. And guess what happens if you try to add an element to it? You cannot.
So, to answer your question, what does ic
point to? Your empty (and zero capacity) box.
ic
refers to an empty array instance. It contains no elements (ic[i]
would throw ArrayIndexOutOfBoundsException
for each value of i
), but it's not null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With