What is the size of reference of a class in Java? Is it constant for a particular JVM and OS irrespective of the class for which the reference is made.
Class A
Class B
Class C
A a;
B b;
C c;
Are the size of a
, b
and c
the same irrespective of the size of A
, B
and C
classes?
Yes, all references are "pointers" to Objects or indirect "pointers to pointers" to Objects. Their actual in memory size is an implementation detail of the JVM but you can be sure that they are equal in size for different classes.
I don't believe it's explicitly specified; it is likely left to the implementation of the JVM to decide (just like System.identityHashcode()
). The relevant section of the JLS certainly doesn't seem to mention any specific size.
It is almost certainly the case that the refernce will actually be a pointer to a memory address, but you shouldn't rely on any specific behaviour of it. In particular, you shouldn't try to manipulate them at all like you would in C for example.
I'm curious as to what you are asking about this for - is it mere curiosity or you plan to make use of the reference size somehow (which would almost certainly be a bad idea)? If it's the latter, then let us know what you're planning to do as there's likely to be a better way to achieve it.
The reference is basically a memory address (yes I know it is a little more than that in Java) and its size is unrelated to the size of the object it points at. The only variance is if you are using a 64 bit JVM, the references will need to be larger to accommodate the larger memory addresses.
As far as bytecode is concerned, a reference behaves much the same as an int
or float
. long
and double
take up two stack slots. So it's as if references are four bytes. However, 64-bit systems often munge this so that they can use 64-bit pointers.
Some JVMs (I believe BEA JRockit for some time and recently added to Sun's) use "compressed oops" which is 32-bits which gets shifted left a few places to enable access tens of GB of memory on 64-bit systems. As well as reducing memory consumption, reducing the reference size also reduces the CPU-memory bandwidth and cache requirements, improving performance despite the extra fiddling.
I believe Azul's version of Hotspot uses 64-bit references, with 48-bits for address and 16-bit type information.