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?
Asked
Active
Viewed 213 times
1
-
Generally speaking, I believe the answer is yes, although Java doesn't actually guarantee that. Also any references to other objects of course those other objects are almost never going to be contiguous with the object that holds their reference. – markspace Jun 09 '21 at 01:16
-
There is no way to ascertain this from Java, and similarly there is no way it can possibly matter to a pure Java program. – user207421 Jun 09 '21 at 04:06
1 Answers
2
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.

Eugene
- 117,005
- 15
- 201
- 306
-
That's what I envisioned. So mem allocation for Objects is akin to array elements which makes sense given an array is an object. Thx. – chappie Jun 10 '21 at 11:54