Java array initialization size is zero
When declaring arrays in Java, we must use the new keyword to dynamically allocate memory
class array { public static void main(String ars[]) { int A[] = new int[10]; System.out.println(A.length); } }
The above code will create a 1D array of 10 elements, 4 bytes each The output is 10 But when you run the following code:
class array { public static void main(String ars[]) { int A[] = new int[0]; System.out.println(A.length); } }
The output is 0 I wonder if Java will allocate some memory for the array when you write a new int [0]? If so, how much?
Solution
Yes, it allocates some memory, but the amount varies depending on the JVM implementation You need to represent in some way:
>A unique pointer (make the array! = every new int [0]), so there must be at least 1 byte > class pointer (for object. Getclass()) > hashcode (system. Identityhashcode) > object monitor (for synchronized (object)) > array length
The JVM can perform various optimizations (export the system hash code from the object pointer if it has not been GC / relocated, use a single bit to represent an unlocked object, use a single bit to represent an empty array), etc.), but it still needs to allocate some memory
Edit: for example, following the steps on this post, my JVM reports that the size of the new int [0] is 16, while for the new int [4], it is 32