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

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


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.


It will be stored on the heap

because array is an object in java.

EDIT : if you have

int [] testScores; testScores = new int[4];

Think of this code as saying to the compiler, "Create an array object that will hold four ints, and assign it to the reference variable named testScores. Also, go ahead and set each int element to zero. Thanks."


It is an array of primitive types which in itself is not primitive. A good rule of thumb is when the new keyword is involved the result will be on the heap.