Reputation: 17886
This is the usual way for declare a Java array:
int[] arr = new int[100];
But this array is using heap space. Is there a way we can declare an array using stack space like c++?
Upvotes: 13
Views: 8695
Reputation: 43150
It's not yet supported as a language feature, because that would require value types since passing on-stack data by reference would not be safe.
But as an optimization (escape analysis) the JVM may already do that for local variables containing small, fixed-size arrays iff it can prove that it does not escape the local/callee scope. That said, it's just a runtime optimization and not some spec guarantee, so relying on it is difficult.
Upvotes: 1
Reputation: 33544
Arrays are objects
irrespective of whether it holds primitive type or object type, so like any other object its allocated space on the heap.
But then from Java 6u23
version, Escape Analysis
came into existence, which is by default activated in Java 7
.
Escape Analysis is about the scope of the object
, when an object is defined inside a method scope rather than a class scope
, then the JVM knows that this object cant escape this limited method scope, and applies various optimization on it.. like Constant folding, etc
Then it can also allocate the object which is defined in the method scope,
on the Thread's Stack, which is accessing the method.
Upvotes: 24
Reputation: 34685
In a word, no.
The only variables that are stored on the stack are primitives and object references. In your example, the arr
reference is stored on the stack, but it references data that is on the heap.
If you're asking this question coming from C++ because you want to be sure your memory is cleaned up, read about garbage collection. In short, Java automatically takes care of cleaning up memory in the heap as well as memory on the stack.
Upvotes: 12
Reputation: 36476
Arrays are dynamically allocated so they go on the heap.
I mean, what happens when you do this:
int[] arr = new int[4];
arr = new int[5];
If the first allocation was done on the stack, how would we garbage collect it? The reference arr
is stored on the stack, but the actual array of data must be on the heap.
Upvotes: 3