Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of zero length in java

Tags:

java

arrays

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)?

enter image description here

like image 600
overexchange Avatar asked Jul 12 '15 12:07

overexchange


People also ask

What is an array of length 0 in Java?

A zero length array is still an instance of Object which holds zero elements.

Can an array have a length of 0?

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.

How do you make an array of length 0?

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.

What is a zero length 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.


3 Answers

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.

like image 156
M A Avatar answered Oct 11 '22 01:10

M A


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.

like image 20
Luigi Cortese Avatar answered Oct 11 '22 00:10

Luigi Cortese


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.

like image 2
Eran Avatar answered Oct 11 '22 02:10

Eran