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?
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.
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.
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.
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).
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With