Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 686
user241924 Avatar asked Jan 20 '10 07:01

user241924


People also ask

Are primitives stored in stack or heap?

There are two kinds of memory used in Java. These are called stack memory and heap memory. Stack memory stores primitive types and the addresses of objects. The object values are stored in heap memory.

Are Java primitives stored on the stack?

➲ In Java, all data type for primitive type variables is stored on the stack. ➲ For reference data types, the stack holds a pointer to the object on the heap.

Is Java array allocated on heap?

Arrays are dynamically allocated so they go on the heap.

Are arrays on the heap or stack?

Unlike Java, C++ arrays can be allocated on the stack. Java arrays are a special type of object, hence they can only be dynamically allocated via "new" and therefore allocated on the heap.


1 Answers

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.

like image 193
Jon Skeet Avatar answered Oct 13 '22 11:10

Jon Skeet