2D Arrays
Overview
A 2D Array is simply an 'Array of Arrays'. It allows you to store data in a visual grid format with Rows and Columns. It is essential for modeling complex grid-based data, such as a Chess board, an Excel spreadsheet, or pixels on a monitor.
Because a 2D array is just an array holding other arrays, the rows do not technically have to be the same length (known as a 'Jagged Array'), though they usually are. Accessing elements requires two index coordinates: matrix[row][col].
Syntax
Notice how board.length gives the number of rows, while board[row].length gives the number of columns in that specific row. Nested for-loops are the standard way to traverse a 2D grid.
public class Main {
public static void main(String[] args) {
// 1. Literal Declaration (3 rows, 3 columns)
int[][] board = {
{1, 2, 3}, // Row 0
{4, 5, 6}, // Row 1
{7, 8, 9} // Row 2
};
// Accessing the number 6 (Row 1, Column 2)
System.out.println(board[1][2]);
// 2. Iterating through a 2D Array
// Outer loop goes through the Rows
for (int row = 0; row < board.length; row++) {
// Inner loop goes through the Columns of the current row
for (int col = 0; col < board[row].length; col++) {
System.out.print(board[row][col] + " ");
}
System.out.println(); // New line after each row
}
}
}Common Pitfalls
- Mixing up Rows and Columns. When accessing
matrix[x][y],xis the Vertical Row going down, andyis the Horizontal Column going right. In mathematics coordinates (x,y), x is horizontal. This flip trips up many beginners. - Out of Bounds on non-square matrices. If your grid is 5 rows by 2 columns, using
matrix.lengthfor both the inner and outer loops will instantly crash when scanning the columns.
Interview Questions
Because a 2D array is just an array of arrays, each inner array can be initialized to a completely different length. For example, Row 0 might have 5 elements, while Row 1 only has 2 elements.
O(N^2). Because you must use nested loops to visit every cell, the total number of operations is N multiplied by N.
Real-World Example
Any grid-based UI or game uses 2D arrays. A classic game of Tic-Tac-Toe uses a 3x3 array to track where the X's and O's have been placed.
char[][] ticTacToe = new char[3][3];
ticTacToe[1][1] = 'X'; // Player claims the exact center squareCheck Your Knowledge
Test your understanding of 2D Arrays with these quick questions.