Integer vs int: with regard to memory
Solution 1:
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
Solution 2:
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?
Solution 3:
int is a primitive data type which takes 32 bits(4 bytes) to store.
When your Java code uses the new operator to create an instance of a Java object, much more data is allocated than you might expect. For example, it might surprise you to know that the size ratio of an int value to an Integer object — the smallest object that can hold an int value — is typically 1:4.
Integer is an object which takes 128 bits (16 bytes) to store int value.
When we creates new Integer using new Operator it allocates memory as per follows.
Class Object(32 bits) - which consist of a pointer to the class information, which describes the object in our case its point to java.lang.Integer class
Flags (32 bits)- It is collection of flags that describes the state of object. Like is it has hash-code, is it array or not i.e. its Shape.
Lock (32 bits) - It stores synchronization information of object. whether the object currently synchronized or not.
Above 3 points are called as metadata of an Object.
- Lastly metadata is followed by the Object data (32 bits) itself. In case of Integer its single int value.
All the above explanation is as per 32 bit processor architecture. It can differ from JVM version and vendor.
Solution 4:
For int: 4 bytes used per element without wrappers, and 16 per element with a wrapper.
A wrapped double reports as 24 bytes per element, with the actual double value as 64 bits (8 bytes).
For more details here