Open In App

Where is the memory allocated for Arrays in Java?

Each time an array is declared in the program, contiguous memory is allocated to it. 

Array base address: The address of the first array element is called the array base address. Each element will occupy the memory space required to accommodate the values for its type, i.e.; depending on the data type of the elements, 1, 4, or 8 bytes of memory are allocated for each element. The next memory address is assigned to the next element in the array. This memory allocation process continues until the number of array elements is exceeded.



JVM memory locations: Before moving to the question of where an array is stored in Java, we must know about the memory locations in JVM (Java Virtual Machine). They are:

Where is the memory allocated for an array in Java?



Memory is allocated in Heap are for the Array in Java.

In Java reference types are stored in the Heap area. As arrays are also reference types, (they can be created using the “new” keyword) they are also stored in the Heap area. Arrays are used to store multiple values ​​in a single variable, instead of declaring separate variables for each value. In Java, an array stores primitive values ​​(int, char, etc) or references (i.e. pointers) to objects.

Single-dimension Array:

int arr[] = new int[5];

The int[] arr is just the reference to the array of five integers. If you create an array with 50 integers, it is the same – an array is allocated and a reference is returned.

int intArray[];    //declaring array
intArray = new int[10];  // allocating memory to array

We use new to allocate an array, you must specify the type and number of elements to allocate.

Array of Objects:

In case of array of objects, the reference to the array is stored in the heap. And the array elements themselves also store the reference to the objects. 

class A{
    . . . 
}

public class Ex{
    public static void main(String[] args) {
        A arr[] = new A[5]
    }
}

Article Tags :