Back to Study Material Java

Multidimensional Arrays in Java

A multidimensional array in Java is an array of arrays. While Java does not have true matrix types like some mathematical languages, it achieves the same e...

Multidimensional Arrays in Java

Working with Matrices and Grids Using 2D Arrays

A multidimensional array in Java is an array of arrays. While Java does not have true matrix types like some mathematical languages, it achieves the same effect by allowing array elements to themselves be arrays. Two-dimensional arrays are the most common form and are used to represent tables, matrices, grids, game boards, and pixel data.

Declaring a two-dimensional array: int[][] matrix;. Creating it: matrix = new int[3][4]; allocates a 3-by-4 array — 3 rows and 4 columns, giving 12 integer elements. All elements are initialized to 0. Accessing elements requires two indices: matrix[row][col]. For a 3-by-4 array, valid row indices are 0, 1, 2 and valid column indices are 0, 1, 2, 3.

You can initialize a 2D array with an array initializer: int[][] grid = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };. This creates a 3-by-3 matrix. Each inner pair of braces initializes one row.

Iterating over a 2D array requires nested loops. The outer loop iterates over rows, the inner loop over columns: for (int r = 0; r < matrix.length; r++) { for (int c = 0; c < matrix[r].length; c++) { System.out.print(matrix[r][c] + " "); } System.out.println(); }. Using matrix[r].length in the inner loop is important because Java 2D arrays are arrays of arrays, and different rows can have different lengths.

Jagged arrays (also called ragged arrays) take advantage of this: each row can have a different number of columns. To create a jagged array, you specify only the number of rows initially and then allocate each row separately: int[][] jagged = new int[3][]; jagged[0] = new int[2]; jagged[1] = new int[4]; jagged[2] = new int[1];. This creates rows of lengths 2, 4, and 1. Jagged arrays are useful for representing triangular data or sparse structures where allocating a full rectangular array would waste memory.

Java supports arrays with more than two dimensions: int[][][] cube = new int[4][4][4]; creates a 4x4x4 three-dimensional array. Three-dimensional arrays appear in scientific computing, 3D graphics, and machine learning for representing tensors. Each additional dimension adds another level of nesting in declarations, creation, and traversal loops.

Passing a multidimensional array to a method: void printMatrix(int[][] m) { ... }. Since arrays are objects, the method receives a reference; changes to the array elements inside the method are visible to the caller.

Interview tip: Matrix-related problems are popular in technical interviews: transposing a matrix, rotating it 90 degrees, multiplying two matrices, or finding the largest sum in a submatrix. Practice these patterns. For the transpose problem, swap matrix[i][j] with matrix[j][i] for all i < j when the matrix is square.