Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer vs int: with regard to memory

Tags:

java

integer

int

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 normally, how about Integer n

like image 213
TimeToCodeTheRoad Avatar asked Dec 07 '11 17:12

TimeToCodeTheRoad


People also ask

What's the difference between int and Integer?

In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it. Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.

How much memory does Integer use?

Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored.

What is the difference between int [] and Integer []?

The major difference between an Integer and an int is that Integer is a wrapper class whereas int is a primitive data type. An int is a data type that stores 32-bit signed two's complement integer whereas an Integer is a class that wraps a primitive type int in an object.


2 Answers

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

like image 168
Noufal Panolan Avatar answered Oct 09 '22 22:10

Noufal Panolan


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?

like image 25
Craig Otis Avatar answered Oct 09 '22 21:10

Craig Otis