5

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

overexchange
  • 15,768
  • 30
  • 152
  • 347

3 Answers3

4

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.

M A
  • 71,713
  • 13
  • 134
  • 174
  • empty array at memory address `659e0bfd` as per above code? – overexchange Jul 12 '15 at 12:06
  • 1
    @overexchange The hash code which was output for the array may be related to the memory address, but it is not the memory address itself. See also http://stackoverflow.com/questions/2237720/what-is-an-objects-hash-code-if-hashcode-is-not-overridden – Christian Semrau Jul 12 '15 at 12:11
  • @overexchange Yes `obj1 == obj2` checks if the two variables refer to the same object in memory. Java has no mechanism for getting memory address. – M A Jul 12 '15 at 15:16
3

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.

Luigi Cortese
  • 10,841
  • 6
  • 37
  • 48
2

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.

Eran
  • 387,369
  • 54
  • 702
  • 768