Java – the size of a reference variable in java. Can it be calculated

java

As pointers in C require 2 bytes of memory size irrespective of the size of the data type they are pointing. So does the same thing applies to java references also ?

Best Answer

The Java Language Specification doesn't say anything about how big a reference is in memory. The JLS doesn't even say that a reference needs to exist at runtime at all. The compiler is free to use 42 gigabytes for a reference or to eliminate it completely, making the size 0 bytes. (In fact, the Java Language Specification never says anything about a particular implementation strategy or representation, it only specifies the syntax and semantics of Java's language constructs, not their pragmatics.)

Most typical Java Implementations will simply implement references as pointers, thus making them the same size as in C. Sometimes, these references are referred to as OOPs (ordinary object pointers). But the Oracle Hotspot JVM, for example, has a feature called CompressedOOPs, which can make some references smaller than C pointers on 64 bit systems.