Search code examples
javavariablesmemory-managementinstance

Are the instance variables for an object stored in continguous memory


Are the instance variables for an object stored in contiguous memory like elements in an array? Say you have Student class def that has a name, age, and grade instance variable. When an instance of the Student class is constructed, are the instance variables stored in contiguous memory?


Solution

  • In general, the answer is yes; but this is un-specified. There is a library specifically designed for this, that you can play around with.

    For example for a class like:

    static class Example {
        byte b = 1;
        int x = 3;
        long l= 12;
    }
    

    You can see its layout (via ClassLayout.parseClass(Example.class).toPrintable()):

     Example object internals:
     OFFSET  SIZE   TYPE DESCRIPTION                               VALUE
          0    12        (object header)                           N/A
         12     4    int Example.x                                 N/A
         16     8   long Example.l                                 N/A
         24     1   byte Example.b                                 N/A
         25     7        (loss due to the next object alignment)
    Instance size: 32 bytes
    Space losses: 0 bytes internal + 7 bytes external = 7 bytes total
    

    Notice how fields have changed their position (to make the padding less), plus the fact that there is a 7 bytes padding.

    Things get more and more interesting the deeper you look into this, like inheritance for example, or for Objects that are made of other Objects. The examples in that library are very rich in this manner.