1

I am little bit confused with java's memory allocation technique. Can anybody help me, how java will allocate memory for following code ?

Integer a;
a = new Integer(1);

I am asking that for Integer a, jvm will create 64 bit reference and a = new Integer(1) for that it will allocate more memory to store value of 1. Is this correct ?

Arpssss
  • 3,850
  • 6
  • 36
  • 80
  • 1
    For Integer type there is a cactch. Integer objects up to 128 are created in advanced and cached. `new Integer` will create a new object, but preferred `Integer.valueOf` will return Integer object from cache. – Piotr Gwiazda Aug 03 '12 at 07:22

2 Answers2

9

Integer a; will allocate memory in stack to hold the reference value and initialized with null

new creates instance in heap memory

jmj
  • 237,923
  • 42
  • 401
  • 438
  • OK. So, in total it will allocate nearly 64+32 bits in memory. Is this correct ? 64 bit jvm – Arpssss Aug 03 '12 at 07:22
  • Yes, if you want to measure the object size then check [this approach](http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object) – jmj Aug 03 '12 at 07:35
  • Won't it take much more memory, because we are using a class instead of the primitive? Doesn't allocate the JVM extra memory for storing private data like information about RTTI etc? – Martijn Courteaux Aug 03 '12 at 07:48
  • Not sure, if you want to measure the object size then [check this approach](http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object) – jmj Aug 03 '12 at 07:49
3

Most JVMs (even 64-bit ones) use 32-bit references. (Newer JVMs uses 32-bit references for heaps up to almost 32 GB) The reference is on the stack or in a CPU register and is not usually counted. The Integer is allocated on the heap.

Integer i = new Integer(1); // creates a new object every time.
Integer j = 1; // use a cached value.

Using auto boxing is not only shorter, but can be more efficient as it can use a cache.

Of course the most efficient is

int k = 1; // not object created and no heap used.

For autoboxed values the performance difference is very small compared with primitives and the reference is likely to be the same size as the int value. However for larger values, there can be a significant performance difference.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130