开发者

Local variable of type string is stored on stack or heap?

I have two local variables in a method as follows,

int i=10;
String test=开发者_如何学JAVA"test";

As far as i know as these variables are local to only a specfic method,these should be stored on a stack,will the string type is also stored on a stack?


The variable itself (the reference to the String instance) will be stored on the stack.

The String instance (which contains the char[] with the actual data) will usually be stored in the heap. It is up to the JVM to optimize this, though. It could be a String from the permgen pool, or if escape analysis is done (and the String is guaranteed to not leave the local scope), it might choose to allocate it on the stack as well.

This is the case for all objects and arrays. Only primitives are different (because they are passed around as value, not as a reference to a data structure allocated elsewhere).


The stack frame will contain the value of the int and the (reference) value of the String. The object that the String reference value points (e.g. the thing that represents the string's characters, length and so on) to will be stored in the heap.

(It is probably easiest to explain this in a picture ... if someone could contribute a link ...)


As stated above, the reference will be on the stack. In Sun's JVM, the actual data would be stored in the perm gen area (since the String in question is a String literal), and would also be added to a weak HashMap which resides on the heap. This is the behavior for interned Strings in the Sun JVM.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜