Reputation: 3369
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?
Upvotes: 7
Views: 319
Reputation: 6657
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
Upvotes: 2
Reputation: 169018
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.
Upvotes: 7