The first thing to understand is that local variables are stored on the stack, which are not explicitly initialized with their default values. Although instance variables are stored in Heap, they are initialized by default to the default value.
In addition, objects are also created on the heap, regardless of whether the reference instance variable contains its own link or local reference variable.
Now, when you declare a reference to an array like this as a local variable and initialize it with an array: -
int[] in = new int[5];
A reference to the array (in) is stored on the stack, and memory is allocated for the array that can hold 5 integer elements on the heap (remember, objects are created on the heap). Then, 5 contiguous memory locations (size = 5) allocated on the heap to store an integer value. And each index of the array object contains a link to this memory cell in sequence. Then the array refers to this array. Thus, since memory for 5 integer values ββis allocated in Heap, they are initialized with a default value.
And also, when you declare a reference to an array and do not initialize it with any array object: -
int[] in;
An array reference is created in Stack (since it is a local variable), but by default it is not initialized by the array, and not to null , as is the case with instance variables.
So, here is what the distribution looks like when you use the first way to declare an array and initialize: -
"Your array reference" "on stack" | | "Array object on Heap" +----+ | in |----------> ([0, 0, 0, 0, 0]) +----+ "Stack" "Heap"
Rohit Jain Nov 22 '12 at 11:36 2012-11-22 11:36
source share