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
For
Integer e1 = 0
Integer been a Wrapper Class goes into heap memory
Please help with the proper understanding?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With