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?
Yes, it allocates some memory, but the amount varies depending on the JVM implementation. You need to somehow represent:
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]
.
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