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";
}
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, thati2will 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 aStringwith the value"abc", then the reference may point to that.