Java (Stack&Heap) - what happens memory wise in th

2019-08-19 05:39发布

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";
}

5条回答
Bombasti
2楼-- · 2019-08-19 06:07

All of them are stored in the heap.

As the SO tag says:

The heap is process memory set aside for dynamic allocation.

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.

查看更多
看我几分像从前
3楼-- · 2019-08-19 06:13

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 to i1, i2, and str. I'm guessing that since you're not in a method, that i2 will be automatically converted behind the scenes to the equivalent of Integer 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 a String with the value "abc", then the reference may point to that.

查看更多
女痞
4楼-- · 2019-08-19 06:23

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.

查看更多
三岁会撩人
5楼-- · 2019-08-19 06:24

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.

查看更多
SAY GOODBYE
6楼-- · 2019-08-19 06:29
public ExampleClass {
   Integer i1=new Integer(1); //heap
   int i2 = 2; //heap
   String str = "abc"; //permGen
}

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.

查看更多
登录 后发表回答