9

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?

1 Answer 1

10

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].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.