Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array using stack space

Tags:

java

arrays

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++?

like image 906
icn Avatar asked Jun 08 '12 18:06

icn


People also ask

Can a stack hold an array in Java?

This tutorial gives example of implementing a Stack data structure using Array. The stack offers to put new object on the stack (method push()) and to get objects from the stack (method pop()). A stack returns the object according to last-in-first-out (LIFO).

Can we store array in stack?

Arrays are stored the same no matter where they are. It doesn't matter if they are declared as local variables, global variables, or allocated dynamically off the heap. The only thing that differs is where they are stored.

How much space does an array take Java?

The memory allocation for an array includes the header object of 12 bytes plus the number of elements multiplied by the size of the data type that will be stored and padding as needed for the memory block to be a multiple of 8 bytes.

How do you add spaces to an array in Java?

Step1: Create an array of size 10, when it is full make a temporary array of array. size*2. Step2: Now add the contents of the first array to the temp array. Step3: Re-initialize the array with a new size (temp array size).


2 Answers

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.
like image 154
Kumar Vivek Mitra Avatar answered Oct 12 '22 23:10

Kumar Vivek Mitra


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.

like image 44
cheeken Avatar answered Oct 13 '22 01:10

cheeken