🌱BeginnerArrays
Multidimensional Arrays
Work with 2D arrays (tables/matrices) in Java - declare, initialise, access, and iterate using nested loops.
Overview
A 2D array is an array of arrays - think of it as a table with rows and columns. It is the natural way to represent matrices, grids, game boards (chess, tic-tac-toe), or any tabular data.
In Java, a 2D array is declared with two sets of brackets: int[][]. The first index selects a row and the second selects a column. You access elements with arr[row][col] and iterate with nested for loops.
Key Points
- •Syntax: `int[][] matrix = new int[rows][cols];`
- •Access: `matrix[rowIndex][colIndex]` - row first, then column
- •Array literal: `int[][] m = {{1,2,3}, {4,5,6}, {7,8,9}};`
- •matrix.length = number of rows; matrix[0].length = number of columns
- •Iterate with nested for loops: outer for rows, inner for columns
- •Java supports "jagged" 2D arrays where rows have different lengths
Examples
Creating and accessing a 2D array
public class Main {
public static void main(String[] args) {
// 3 rows, 3 columns
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(grid[0][0]); // 1 (row 0, col 0)
System.out.println(grid[1][2]); // 6 (row 1, col 2)
System.out.println(grid[2][1]); // 8 (row 2, col 1)
System.out.println("Rows: " + grid.length); // 3
System.out.println("Cols: " + grid[0].length); // 3
}
}grid[row][col] - row index is always first.
Printing a 2D array with nested loops
public class Main {
public static void main(String[] args) {
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.printf("%3d", matrix[row][col]);
}
System.out.println(); // new line after each row
}
}
}%3d formats the integer in a 3-character wide field, aligning columns.
Tic-tac-toe board
public class Main {
public static void main(String[] args) {
char[][] board = {
{'X', 'O', 'X'},
{'O', 'X', 'O'},
{'O', 'X', 'X'}
};
// Print the board
for (char[] row : board) {
for (char cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
// Check if centre is X
System.out.println("Centre is X: " + (board[1][1] == 'X')); // true
}
}for-each works on 2D arrays too - the outer loop yields each row (a 1D char[]).
Common Mistakes
- Swapping row and column: `grid[col][row]` instead of `grid[row][col]`
- Accessing out of bounds: using `matrix.length` as both row and column count when they differ
- Thinking all rows must be the same length - Java allows jagged arrays, but it can lead to bugs if not handled carefully
Note
For matrices, use `matrix.length` for the number of rows and `matrix[i].length` for the number of columns in row i. This works correctly even with jagged arrays.
Exercises
Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.
Loading editor…
Completed: 0 / 4 exercises
Knowledge Check
Question 1 of 4