Java Multidimensional Arrays
What is a 2D Array?
A two-dimensional array represents a grid of values — rows and columns — which is useful for things like game boards, matrices, seating charts, or spreadsheets. In Java, a 2D array is really an array of arrays: the outer array holds references to inner arrays, each of which is a regular 1D array.
Declaring a 2D Array
// 3 rows, 4 columns, all values default to 0
int[][] grid = new int[3][4];
// Declare and fill with literal values
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};Accessing Elements with grid[i][j]
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[0][0]); // first row, first column
System.out.println(matrix[1][2]); // second row, third column
matrix[2][0] = 100; // update bottom-left value
System.out.println(matrix[2][0]);1 6 100
Traversing with Nested Loops
The standard way to visit every element of a 2D array is a nested for loop — the outer loop walks the rows, the inner loop walks the columns of the current row.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}1 2 3 4 5 6 7 8 9
"Arrays of Arrays": Jagged Arrays
Because a Java 2D array is genuinely an array of separate array objects, there's no rule that every row has to be the same length. You can build a JAGGED array, where each row has its own, independent size. This is a real Java-specific flexibility that languages with true fixed-size matrices don't offer.
int[][] triangle = new int[4][];
triangle[0] = new int[] {1};
triangle[1] = new int[] {1, 2};
triangle[2] = new int[] {1, 2, 3};
triangle[3] = new int[] {1, 2, 3, 4};
for (int[] row : triangle) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}1 1 2 1 2 3 1 2 3 4
Rectangular vs Jagged
Aspect | Rectangular 2D array | Jagged array |
Row lengths | All equal | Can differ per row |
Declaration | new int[rows][cols] | new int[rows][], then fill rows individually |
Typical use | Matrices, grids, game boards | Triangular data, variable-length records per row |
Practice Exercises
Create a 4x4 int matrix, fill it with the row number times the column number, then print it as a grid.
Write a method that sums all the values in a 2D int array using nested loops.
Build a jagged array representing Pascal's triangle for 5 rows.