Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the reference variable in Java have any size?

Tags:

java

c

In C++ we used sizeof() operator, which function can we use in Java to check the size of an object?

My basic doubt is that whether the reference variable in java has any size or not. Consider the following example:

SampleClass obj = new SampleClass();

Here, will obj have any size? If yes, How can we check it in Java?

like image 603
Anit Singh Avatar asked Oct 11 '11 18:10

Anit Singh


People also ask

What is size of reference variable in Java?

on a 32-bit JVM, it will be 32 bits. on a 64-bit JVM, it can be 32 or 64 bits depending on configuration. On hotspot for example, compressed ordinary object pointers is activated by default and the size of a reference is 32 bits.

Are all reference variables the same size in Java?

Examples of primitive data types are int, float, double, Boolean, long, etc. JVM allocates 8 bytes for each reference variable, by default. Its size depends on the data type.

What is reference variable in Java?

Reference variable is used to point object/values. 2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference variables hold the objects/values of reference types in Java.

Does reference Take memory in Java?

In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on the heap (See this for more details).


1 Answers

obj is a variable, not an object. The value of obj is a reference - which is likely to be 4 or 8 bytes, depending on the JVM.

The size of the object that the value refers to is also JVM-dependent. As several objects can refer to each other, it's generally tricky to talk about the size of an object in Java in any particularly useful way... what usually matters is how much more memory would be potentially available if a particular object became eligible for garbage collection, and that depends on what other objects the first object refers to - and whether there are other objects that refer to those, too.

Obviously the "raw" size of an object is somewhat important too, and at least somewhat easier to predict (to an approximation, at least), but it's still VM-specific and can't easily be requested at execution time. (You could create millions of objects, prevent them from being garbage collected, and measure memory differences, but that's the closest I know of, at least outside a debugger API.)

like image 70
Jon Skeet Avatar answered Oct 23 '22 05:10

Jon Skeet