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 ?
4
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.
Because of -XX:+UseCompressedOops
JVM HotSpot option, object references are 8 bytes.
Enables the use of compressed pointers (object references represented as 32 bit offsets instead of 64-bit pointers) for optimized 64-bit performance with Java heap sizes less than 32gb.
We can test this by adding a reference to an empty class and measuring its memory usage. This shows 24 bytes used on the heap. Add one more “byte” primitive, measure again and you’ll see 32 bytes of heap usage.
2