Array Memory Allocation:
In Java, arrays are objects that are dynamically allocated in memory.
Key Points:
1. Declaration: When you declare an array, you only specify its type and name. No memory is
allocated at this stage.
2. int[] arr;
3. Instantiation: Memory is allocated when you use the new keyword to create the array and
specify its size.
4. arr = new int[5];
5. Initialization: You can initialize the array elements either at the time of allocation or later.
6. int[] arr = {1, 2, 3, 4, 5};
7. Memory Allocation:
o Arrays are stored in heap memory because they are objects.
o The reference to the array is stored in the stack memory.
o Each element in the array is initialized to its default value (e.g., 0 for integers, null for
objects, false for booleans).
Example:
Copy the codepublic class ArrayExample {
public static void main(String[] args) {
int[] numbers;
numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
for (int num : numbers) {
System.out.println(num);
}
Notes:
Arrays in Java are fixed in size once allocated.
If you need a resizable array, consider using classes like ArrayList from the java.util package.
Java performs automatic garbage collection, so you don't need to manually free the memory
allocated for arrays.
Diagram:
Diagram:2
Diagram:3