How much actual memory does an object occupy
Instances of an object on the Java heap don’t just take up memory for their actual fields. Inevitably, they also require some “housekeeping” information, such as recording an object’s class, ID and status flags such as whether the object is currently reachable, currently synchronization-locked etc.
– a normal object requires 8 bytes of “housekeeping” space;
– arrays require 12 bytes (the same as a normal object, plus 4 bytes for the array length).
Object size granularity
In Hotspot, every object occupies a number of bytes that is a multiple of 8. If the number of bytes required by an object for its header and fields is not a multiple 8, then you round up to the next multiple of 8.
This means, for example, that:
– a bare Object takes up 8 bytes;
– an instance of a class with a single boolean field takes up 16 bytes: 8 bytes of header, 1 byte for the boolean and 7 bytes of “padding” to make the size up to a multiple of 8;
– an instance with eight boolean fields will also take up 16 bytes: 8 for the header, 8 for the booleans; since this is already a multiple of 8, no padding is needed;
– an object with a two long fields, three int fields and a boolean will take up:
8 bytes for the header;
16 bytes for the 2 longs (8 each);
12 bytes for the 3 ints (4 each);
1 byte for the boolean;
a further 3 bytes of padding, to round the total up from 37 to 40, a multiple of 8.