开发者

Does initialized java array go onto stack or heap?

开发者 https://www.devze.com 2023-01-11 22:35 出处:网络
void someMe开发者_StackOverflow中文版thod() { byte[] array = { 0, 0 }; } Will this array be stored in heap or on the stack?You can think of it as always going on the heap.
void someMe开发者_StackOverflow中文版thod() {
  byte[] array = { 0, 0 };
}

Will this array be stored in heap or on the stack?


You can think of it as always going on the heap.

I believe some smart VMs are able to stack-allocate objects if they can detect it's safe - but conceptually it's on the heap. In particular, all array types are reference types (even if the element type is primitive), so the array variable (which is on the stack) is just a reference to an object, and objects normally go on the heap.

In particular, imagine a small change:

byte[] someMethod() { 
    byte[] array = { 0, 0 };
    return array;
}

If the array were allocated on the stack, what would the returned reference have to refer to?


It will be stored in the heap

0

精彩评论

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