Amar
Amar

Reputation: 441

Java Wrapper & Primitive Memory Allocation

I was asked following question in a interview

Consider this following Code

int i =0
Integer e1 = 0
In which memory are they going to be created?

As per my understanding

For int i =0

Primitive data type goes into stack memory and

ForInteger e1 = 0

Integer been a Wrapper Class goes into heap memory

Please help with the proper understanding?

Upvotes: 12

Views: 4526

Answers (2)

JamesC
JamesC

Reputation: 496

This one is a very interesting question.

With the primitive the allocation will be in the stack and will cost its needed 4 bytes give or take some rounding.

But things really begin to grow when talking about the wrapper. If we compare it to C++, the fact that the 4 bytes will be allocated in the heap, makes the e1 a pointer.

Assuming we are using a 64bit machine, e1 will take 8bytes in the stack (+rounding).

And the heap data chunk has at least a small 4-8bytes header.

Looking inside the implementation of these types I don't see more memory used for each instance as all helper members and constants are static, so all instances will use the same data chunk in the 'data-segment' used for this type.

So, adding all this shows that the wrapper's allocation will always be bigger than the primitive. For example - with extremely rough calculation you get something like:

Primitive: int -> 4 bytes, Wrapper: Integer -> 8(stack) + 4 + 4 = 16 bytes

As for performance, it seems that primitives will be manipulated way faster than wrappers, but this is for another discussion.

Hope this info had helped.

Upvotes: 1

Stephen C
Stephen C

Reputation: 718768

It is a bit more complicated than that.

First, you need to know whether the i and ei variables are local variables or fields (static or instance) of an object1.

If they are local variables:

  • i is on the stack.
  • ei is on the stack (a reference) and it refers to an object in the heap.

If they are fields of an instance or class:

  • i is on the heap (as part of the instance or the class).
  • ei is on the heap (as part of the instance or the class) and it refers to an object in the heap.

Finally, it is worth noting that Integer e1 = 0 may not allocate a new Integer object at all. The reference stored in e1 may be a reference to an object that already existed.


1 - There's another case too. If i or ei are local variables that are referred to by an inner class declaration, then a second copy will be made when the inner class is instantiated. For that copy, the space usage will be as if i / ei were fields of the inner class.

Upvotes: 16

Related Questions