-1

I am finding how much memory each of the variable consumes in a sample piece of code of I am writing by referring http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

class A{
    public static void main(String[] args){
        int a;        // 4 bytes
        int b = 2;    // 4 bytes
        char c = 'a'; // 2 bytes
        B d;          // 8 bytes, reference to a 64bit memory takes up 8 bytes
        B e = new B();// 12 bytes, 8 bytes for reference + 4 bytes for int within it
    }
}

class B{
    int x; 
}

I am trying to understand the memory footprint of a simple java program here. Are my understanding of memory footprint correct here. Also I want to know how much does each class consume. If class B did not have any fields in it, is there is still a B.class file generated and what does it contain.

Anoop
  • 5,540
  • 7
  • 35
  • 52

1 Answers1

1

It is worth remembering that local variables are allocated to registers, on a 64-bit machine these are 64-bit, and may or may not use any memory.

Each object has a 8 (32-bit) to 12 (64-bit) header. Also objects are padded by at least 8 byte alignment. i.e. each B uses 16 bytes. The reference to it is 4 bytes.

BTW: a references is usually 32-bit on a 64-bit JVM by using Compressed Oops to address between 32 GB (up to Java 7) and 64 GB (Java 8) of memory.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    How much memory for example an object uses is implementation-dependent. The above might all be true for Oracle's JVM on Windows, but might be different on other OSes or with other JVM implementations. – Jesper Dec 28 '14 at 09:25
  • @Jesper While implementation dependant this applies to OpenJDK (the reference implementation), Oracle, Azul and AFAIK IBM's JVM. Android DVM for example could be completely different. – Peter Lawrey Dec 28 '14 at 10:29
  • @Jesper This suggests the header is 8 bytes on a 32-bit DVM http://www.netmite.com/android/mydroid/dalvik/vm/oo/Object.h – Peter Lawrey Dec 28 '14 at 10:31