i gets auto-boxed to an Integer when passed to getObjectSize.
So you get the value of the size of promoted variable, not the original primitive int.
To circumvent this behaviour, build overloads of getObjectSize for the primitive cases:
public static long getObjectSize(int o) {
return Integer.SIZE / 8;
}
and so on.
Answer from Bathsheba on Stack OverflowVideos
i gets auto-boxed to an Integer when passed to getObjectSize.
So you get the value of the size of promoted variable, not the original primitive int.
To circumvent this behaviour, build overloads of getObjectSize for the primitive cases:
public static long getObjectSize(int o) {
return Integer.SIZE / 8;
}
and so on.
intis a primitive type and it size 4 bytes andIntegeris reference type and its size is 16 bytes. In this case, why does it retuyrn 16 bytes for both the values?
Because the ObjectSizeFetcher.getObjectSize(Object) call is autoboxing the int to an Integer.
AFAIK, there is no standard API to measure the size of a primitive type, or a reference. One reason is that the size will depend on where / how it is stored. For example, a byte stored in a (large) byte[] will most likely take less space than a byte stored as a field of an object. And a byte held is a local variable could be different again. (There are issues of packing and alignment to tack account of.)
It is simple to write overloaded methods to return constant minimum size for each primitive types. References are a bit more tricky because the size of a reference depends on whether you are using a 32 or 64 bit JVM, and whether compressed oops are enabled.
In general, the heap memory used by a Java object in Hotspot consists of:
- an object header, consisting of a few bytes of "housekeeping" information;
- memory for primitive fields, according to their size (int n->32 bits)
- memory for reference fields (4 bytes each) (Integer n ->32 bits)
- padding: potentially a few "wasted" unused bytes after the object data, to make every object start at an address that is a convenient multiple of bytes and reduce the number of bits required to represent a pointer to an object.
as per the suggestion of Mark Peters I would like add the link below http://www.javamex.com/tutorials/memory/object_memory_usage.shtml
An Integer object in Java occupies 16 bytes.
I don't know whether running a 64- vs 32-bit JVM makes a difference. For primitive types, it does not matter. But I can not say for certain how the memory footprint of an object changes (if at all) under a 64-bit system.
You can test this for yourself here:
Java Tip 130: Do you know your data size?
I am writing a program and I need the user to input an ID number that is 5 digits long but no shorter or longer. Is there an easy way to check int length from user input in java? Thank you.