Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
782 views
in Technique[技术] by (71.8m points)

oop - What is the size of the object in java

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...