Phase 7 of 20 · Topic 7.1

1D & 2D Array Heap Allocation & Memory Contiguity

1Concept

In Java, all arrays are full objects dynamically allocated on the Heap. A 1D primitive array stores contiguous elements in memory. A 2D array is an array of object references, where each reference points to an independent 1D array in the Heap (non-contiguous memory blocks).

2Architecture Diagram

Heap Memory Layout (2D Array: int[3][2]):
[ Root Array Ref ] ---> [ [Ref 0] | [Ref 1] | [Ref 2] ] (Row array)
                             |         |         |
                             v         v         v
                          [e0, e1]  [e0, e1]  [e0, e1]

3Code Example

Core Java
public class ArrayMemoryDemo {
    public static void main(String[] args) {
        // 1D Primitive Array
        int[] numbers = new int[]{10, 20, 30, 40, 50};
        System.out.println("1D Array Length: " + numbers.length);
        System.out.println("First Element: " + numbers[0]);

        // 2D Array Matrix
        int[][] grid = {
            {1, 2},
            {3, 4},
            {5, 6}
        };
        System.out.println("2D Grid Rows: " + grid.length + ", Columns: " + grid[0].length);
        System.out.println("grid[1][1] Value: " + grid[1][1]);
    }
}

4Expected Output

1D Array Length: 5
First Element: 10
2D Grid Rows: 3, Columns: 2
grid[1][1] Value: 4

5Key Takeaways

  • Array indices are always 32-bit integers (max size: Integer.MAX_VALUE - 8).
  • Arrays are initialized to defaults automatically (0 for numerics, false for booleans, null for references).
  • Java does not support true contiguous multi-dimensional matrices like C/C++.