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.
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.
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:
Now, where does
f.value
live? The myth would suggest it's on the stack - but actually it's part of the newFoo
object, and lives on the heap1. (Note that the value off
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: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 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.
In the Java programming language arrays are objects, are dynamically created, and may be assigned to variables of type Object.
http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html
I just wanted to share few tests I ran on this subject.
Array of size 10 million
Output:
As you see used heap size is increased by ~80 MB, which is 10m * sizeof(double).
But if we have use Double instead of double
Output will show 40MB. We only have Double references, they are not initialized.
Filling it with Double
Still 40MB. Because they all point to same Double object.
Initializing with double instead
Line
is equivalent to
which is equivalent to
Since we create new Double objects each time, we blow out the heap. This shows values inside the Double class are stored in heap.
It will be stored on the heap
because array is an object in java.
EDIT : if you have
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 eachint
element to zero. Thanks."