Is a Java array of primitives stored in stack or heap?

user241924 picture user241924 · Jan 20, 2010 · Viewed 40.5k times · Source

I have an array declaration like this:

int a[];

Here a is an array of primitive int type. Where is this array stored? Is it stored on heap or stack? This is a primitve type int, all primitive types are not stored on heap.

Answer

Jon Skeet picture Jon Skeet · Jan 20, 2010

As gurukulki said, it's stored on the heap. However, your post suggested a misunderstanding probably due to some well-intentioned person propagating the myth that "primitives always live on the stack". This is untrue. Local variables have their values on the stack, but not all primitive variables are local...

For example, consider this:

public class Foo
{
    int value;
}
...

public void someOtherMethod()
{
    Foo f = new Foo();
    ...
}

Now, where does f.value live? The myth would suggest it's on the stack - but actually it's part of the new Foo object, and lives on the heap1. (Note that the value of f itself is a reference, and lives on the stack.)

From there, it's an easy step to arrays. You can think of an array as just being a lot of variables - so new int[3] is a bit like having a class of this form:

public class ArrayInt3
{
    public readonly int length = 3;
    public int value0;
    public int value1;
    public int value2;
}

1 In fact, it's more complicated than this. The stack/heap distinction is mostly an implementation detail - I believe some JVMs, possibly experimental ones, can tell when an object never "escapes" from a method, and may allocate the whole object on the stack. However, it's conceptually on the heap, if you choose to care.