Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 605
Amar Avatar asked Apr 16 '16 06:04

Amar


1 Answers

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.

like image 109
Stephen C Avatar answered Oct 15 '22 15:10

Stephen C