views:

268

answers:

2

Programing languages like C,C++ will not store array values in Heap rather it keeps the value in STACK. But in Java why there is a necessity to keep array values in heap?

+11  A: 

In Java, arrays (just like all other objects) are passed around by reference: When you pass an array to a method, it will get a reference pointing to the same location in memory, no copy is being made. This means that the array needs to remain "alive" after the method that created it, and so cannot be stored in the stack frame for the method. It needs to managed by the garbage collector, just like all other objects.

There is some research going in to optimize JVM memory allocation using "escape analysis": If an object (such as an array) can be guaranteed to never leave the current scope, it becomes possible to in fact allocate it on the stack, which is more efficient.

Thilo
+5  A: 

A short answer is that an array in Java is a reference type, and reference types live on the heap. It's worth noting that in C#, one can switch to unsafe mode and initialise arrays with stackalloc which will create the array on the stack. It's therefore quite probable that the VM would allow you to make an array on the stack, and it's merely an implementation detail that means arrays all live on the heap.

AlecZorab
Your terminology is not very precise. Reference types do not live on the heap; *objects*, to which those reference types refer, live on the heap. Since an array is an object in Java, it lives on the heap.
Jesper
Quite right. My use of "reference type" and "value type" is in line with the .Net usages, which is, as you say, rather imprecise.
AlecZorab