Christian
Christian

Reputation: 103

Does initialized java array go onto stack or heap?

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

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

Upvotes: 10

Views: 2448

Answers (2)

Jeroen Rosenberg
Jeroen Rosenberg

Reputation: 4682

It will be stored in the heap

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500015

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?

Upvotes: 18

Related Questions