This probably doesn't even need asking, but I want to make sure I'm right on this. When you create an array of any object in Java like so:
Object[] objArr = new Object[10];
The variable objArr
is located in stack memory, and it points to a location in the heap where the array object is located. The size of that array in the heap is equal to a 12 byte object header + 4 (or 8, depending on the reference size) bytes * the number of entries in the array. Is this accurate?
My question, then, is as follows. Since the array above is empty, does it take up 12 + 4*10 = 52 bytes of memory in the heap immediately after the execution of that line of code? Or does the JVM wait until you start putting things into the array before it instantiates it? Do the null references in the array take up space?
According to the 64-bit memory model, an int is 4 bytes, so all the elements will be 4*N bytes in size. In addition to that, Java has a 24 bytes array overhead and there's also 8 bytes for the actual array object. So that's a total of 32 + 4 * N bytes.
Object headers and Object references In a modern 64-bit JDK, an object has a 12-byte header, padded to a multiple of 8 bytes, so the minimum object size is 16 bytes. For 32-bit JVMs, the overhead is 8 bytes, padded to a multiple of 4 bytes. (From Dmitry Spikhalskiy's answer, Jayen's answer, and JavaWorld.)
Each data member takes up 4 bytes, except for long and double which take up 8 bytes. Even if the data member is a byte, it will still take up 4 bytes! In addition, the amount of memory used is increased in 8 byte blocks.
In Java, arrays are objects, therefore just like other objects arrays are stored in heap area. An array store primitive data types or reference (to derived data) types Just like objects the variable of the array holds the reference to the array.
The null references do "take up space" -- the array's memory is allocated up-front in one chunk, and zeroed (to make all of the contents null references). As an exercise, try allocating a huge array, one that will take up more space than your JVM's memory limit. The program should immediately terminate with an out of memory error.
I think this will be helpful to you
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
System.gc();
System.out.println("Before " + r.freeMemory());
Object[] objArr = new Object[10];
System.out.println("After " + r.freeMemory());
objArr[0] = new Integer(3);
System.gc();
System.out.println("After Integer Assigned " + r.freeMemory());
}
Output
Before 15996360
After 15996360
After Integer Assigned 16087144
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