Anyone could explain what happens memory wise (Stack & Heap) in this example? If I understand it correctly, java stores objects on the heap, so i1 will be on the heap... same with string? But what about i2, considering it is a class field declaration.
public ExampleClass {
Integer i1=new Integer(1);
int i2 = 2;
String str = "abc";
}
All of them are stored in the heap.
As the SO tag says:
So any variable will be placed on the heap.
However, any primitive types (
int
,float
, etc) will be stored on the stack **Only if they are allocated locally inside a method).Look here for more info.
Nothing happens until you have some code like
new ExampleClass()
. Once you do that, a new object is allocated on the heap. Included in that will be references toi1
,i2
, andstr
. I'm guessing that since you're not in a method, thati2
will be automatically converted behind the scenes to the equivalent ofInteger i2 = new Integer(0)
. All 3 of these references will be pointing to objects also allocated on the heap. Note that strings are immutable so if there is already aString
with the value"abc"
, then the reference may point to that.Very concise:
Stack: [i1-addr, 2, str-addr]
Heap : [i1-addr : 1, str-addr : 'a','b','c']
. For heap I use notation[addres: value]
. Of course, heap apart of value heap contains some object information (e.g. link to .class object) also.All the initialised values are set in the constructor. While in the constructor, the references are placed on the stack and then the fields on the heap. Once the constructor returns, the reference to the object itself is still on the stack, but all the fields are only on the heap.
In stack stores only local instances/primitives available only to one thread, heap is a shared place (available to any number of threads), permGen is an another part of java memory used to store interned string and loaded classes.