What is the size of the object in java

后端 未结 5 2003
半阙折子戏
半阙折子戏 2020-12-11 19:16

As we all know that java uses the following data types

byte    Occupy 8 bits in memory
short   Occupy 16 bits in memory
int     Occupy 32 bits in memory
long         


        
5条回答
  •  时光取名叫无心
    2020-12-11 19:22

    The header of an object can take 8 bytes on a 32-bit JVM and 12 bytes on a 32-bit JVM.

    Each primitive takes the number of bits (not bytes you indicate)

    Object allocation is 8 byte aligned so there is up to 7 bytes of padding at the end of a object. i.e. the space actually used is rounded up to the next multiple of 8.

    class Demo{ // 8 or 12 bytes
        byte b; // 1 byte
        int i;  // 4 bytes
        long l; // 8 bytes
    }
    
    Demo obj = new Demo();
    

    So the size of the object can take 24 bytes on a 32-bit JVM and 32 bytes on a 64-bit JVM.

提交回复
热议问题