Phase 7 of 20 · Topic 7.5

Array Boundary Safety & Memory Cache Locality

1Concept

The JVM automatically checks every array index access against `0` and `array.length - 1`, throwing `ArrayIndexOutOfBoundsException` on violation to eliminate C-style buffer overflow exploits. Row-major traversal matches CPU cache line loading, running up to 10x faster than column-major traversal.

2Architecture Diagram

CPU L1 Cache Line (64 Bytes):
Row-Major:    [e00, e01, e02, e03] ---> Loaded together into Cache Line (Cache Hit!)
Column-Major: [e00] ... [e10] ... ---> Jumping across memory strides (Cache Miss!)

3Code Example

Core Java
public class CacheLocalityDemo {
    public static void main(String[] args) {
        int rows = 1000, cols = 1000;
        int[][] matrix = new int[rows][cols];

        // Row-major traversal (CPU Cache Friendly)
        long start = System.nanoTime();
        long sum = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                sum += matrix[r][c];
            }
        }
        long elapsed = System.nanoTime() - start;
        System.out.printf("Row-Major Access Sum: %d (Time: %.3f ms)%n", sum, elapsed / 1e6);
    }
}

4Expected Output

Row-Major Access Sum: 0 (Time: 1.450 ms)

5Key Takeaways

  • Row-major iteration maximizes CPU L1/L2 cache hits due to contiguous memory spatial locality.
  • The JVM JIT compiler performs loop bounds-check elimination for standard idiom loops.
  • Array length is fixed at creation time; use ArrayList when dynamic resizing is required.