Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array initialization with zero size

While declaring an array in java we have to dynamically allocate the memory using new keyword.

class array
{
  public static void main(String ars[]) { 
    int A[] = new int[10];
    System.out.println(A.length);
  }
}

Above code will create a 1D array containing 10 elements, 4 byte each. and the output will be 10. But when you run same code as following:

class array { 
  public static void main(String ars[]) {
    int A[] = new int[0];
    System.out.println(A.length);
  }
}

Output is 0. I want to know that when you write new int[0] then do Java allocate some memory for the array or not? If yes how much?

like image 873
Rohit Negi Avatar asked May 16 '15 05:05

Rohit Negi


1 Answers

Yes, it allocates some memory, but the amount varies depending on the JVM implementation. You need to somehow represent:

  1. A unique pointer (so that the array is != every other new int[0]), so at least 1 byte
  2. Class pointer (for Object.getClass())
  3. Hash code (for System.identityHashCode)
  4. Object monitor (for synchronized (Object))
  5. Array length

The JVM might perform various optimizations (derive the system hash code from the object pointer if it hasn't been GC'ed/relocated, use a single bit to represent a never-locked object, use a single bit to represent an empty array, etc.), but it still has to allocate some memory.

Edit: For example, following the steps on this post, my JVM reports a size of 16 for new int[0] vs 32 for new int[4].

like image 135
Brett Kail Avatar answered Oct 03 '22 23:10

Brett Kail