Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the size of the object in java

Tags:

java

oop

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    Occupy 64 bits in memory 

If I create a class like

class Demo{
    byte b;        
    int i;
    long l;
}

Demo obj = new Demo();

Now my question is obj size is < or > or = the size of b+i+l which is 104 bytes. Please give me the clarification with proper reason.

Thanks,
Anil Kumar C

like image 202
Anil Kumar C Avatar asked May 11 '12 10:05

Anil Kumar C


1 Answers

From http://www.javamex.com/tutorials/memory/object_memory_usage.shtml

  1. a bare Object takes up 8 bytes;
  2. 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;
  3. 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;
  4. 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.
like image 198
Calin Andrei Avatar answered Sep 17 '22 07:09

Calin Andrei