Integer vs int: with regard to memory

前端 未结 4 1057
春和景丽
春和景丽 2020-11-28 08:45

I was wondering if there is a difference in the memory occupied by Integer n, and int n.

I know int n occupies 4 bytes normal

4条回答
  •  臣服心动
    2020-11-28 09:10

    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.

    1. 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

    2. 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.

    3. 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.

    1. 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.

提交回复
热议问题