Initializing 2D Arrays with new
What you'll learn: How to allocate memory for rectangular 2D arrays dynamically by specifying their dimensions.
The Core Idea
Just like you used new to create a one-dimensional array, you can use new to create a two-dimensional array by specifying both the number of rows and columns. This allocates a rectangular grid in memory, with each element initialized to its default value (0 for integers, false for booleans, etc.).
The syntax follows this pattern:
type[][] arrayName = new type[rows][columns];
For example, to create a 2D array to represent a 3×4 grid of integers:
int[][] grid = new int[3][4];
This creates an array with 3 rows and 4 columns—essentially a table with 12 integer elements, all initialized to 0.
Analogy: Building a Storage Warehouse
Think of it like ordering a storage facility with a specific layout. When you say new int[3][4], you're telling Java: "Build me a warehouse with 3 aisles (rows), and put 4 shelves (columns) in each aisle." Java constructs this structure and fills every shelf with a default item (zero for int).
Memory Allocation
Behind the scenes, Java creates an array of 3 elements, where each element is itself an array of 4 integers. The dimensions must be specified at creation time for a rectangular array.
double[][] temperatures = new double[7][24]; // 7 days, 24 hours
boolean[][] seats = new boolean[10][15]; // 10 rows, 15 seats per row
Key Takeaway: Use new type[rows][columns] to allocate a rectangular 2D array with specified dimensions; all elements are automatically initialized to their default values.