how does jvm allocate memroies when creating array with non literal size

Viewed 157

In c/c++, it is a must to specifiy a literal number of the array size when creating, i.e. int arr[10];. But in java, we can create an array in this form int size = 10; int[] arr = new int[size];. And the compiler will not figure out what actually the variable size is. Then how does jvm allocate the memeories the array needs ?

3 Answers

Java allocates the array memory on the heap. The variable arr is just a reference to the array, not the array itself. This is the same as allocating an array in c/c++ with malloc or new.

In JVM based languages, Java being the most popular, memory allocation happens at runtime, usually on the heap. However, there are ways to get off-heap memory allocation, which have to be handled by the application itself, and can never be garbage-collected or cause additional overhead.

In int arr[10]; array is determine the size at compile time and in int size = 10; int[] arr = new int[size]; array is determine the size at run time. you can also create dynamic array in c++ which create on run time.

Detail :

In c++,

int arr[10]; this array is allocated on stack and decide the size of an array on compile time

int *arr = new int[10]; this array allocated on heap and decide the size of an array on run time.

In Java, array is always created with new keyword and they created on Heap.

int[] arr = new int[size];

int[] arr is the reference to an integer array in java and in C++ int *arris a pointer to an integer array. So, you can also achieve this in c++.

Related