What is the size of the memoy array of Java objects after it is created?

This probably doesn't even need to be asked, but I want to make sure that I'm right. When you create an array of any object in Java, for example:

Object[] objArr = new Object[10]; 

The objArr variable is on the memory stack and points to the place on the heap where the array object is located. The size of this array on the heap is equal to the 12-byte object header + 4 (or 8, depending on the reference size) bytes * the number of entries in the array. That's for sure?

So my question is this. Since the array above is empty, does it occupy 12 + 4 * 10 = 52 bytes of memory on the heap immediately after this line of code is executed? Or does the JVM wait until you start putting things into an array before it creates it? Are null references in the array taking up space?

+7
source share
2 answers

Zero links take up space - the memory of the array is allocated up in one block and zeroed out (to make all contents null references). As an exercise, try allocating a huge array that will take up more space than your JVM memory limit. The program should immediately exit with an error from memory.

+7
source

I think it will be useful for 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()); } 

Exit

 Before 15996360 After 15996360 After Integer Assigned 16087144 
+2
source

All Articles