A two-dimensional array can represent a table, matrix, board, or map. It is an “array of arrays”: the first index selects a row and the second selects a column in that row. Both start at 0.
Creating and accessing
int[][] grid = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
System.out.println(grid[0][0]); // 1
System.out.println(grid[1][2]); // 7Row-column coordinate navigator
Select a value and watch the first index choose a row and the second choose a column.
KNOWLEDGE QUIZ
Rows and columns
In this section, every row has the same column count. grid.length is the row count and grid[0].length is the column count.
int[][] triangle = {
{1, 0, 0},
{1, 2, 0},
{1, 2, 3}
};
System.out.println(triangle.length); // 3
System.out.println(triangle[0].length); // 3KNOWLEDGE QUIZ
Nested loops
The outer loop controls rows and the inner loop controls columns. Use grid[row].length as the inner bound so the dimension stays connected to the array.
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.printf("%4d", grid[row][col]);
}
System.out.println();
}KNOWLEDGE QUIZ
Matrix addition
Matrix addition and subtraction require matching shapes. The result at position i,j uses only the elements at that same position in the two inputs.
int[][] a = {{1, 3}, {1, 0}, {1, 2}};
int[][] b = {{0, 0}, {7, 5}, {2, 1}};
int[][] c = new int[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}Matrix addition, one cell at a time
The two input matrices stay on the left while the result starts empty. Each click computes exactly one matching cell.
C[0][0] = 1 + 0 = 1The purple cells mark the values read and written in this step.
KNOWLEDGE QUIZ
Statistics over a 2D array
First decide the scope: one row, one column, or the whole table. This code averages one row; converting to double avoids integer division.
int row = 1;
int sum = 0;
for (int col = 0; col < grid[row].length; col++) {
sum += grid[row][col];
}
double average = sum / (double) grid[row].length;Add two matrices
Create two 3×2 int arrays, use nested loops to build their sum, and print the result as 3 rows and 2 columns. Do not write each sum manually.
- Store A, B, and result C in two-dimensional arrays.
- Use nested loops over the same row and column coordinates.
- Compute C[row][col] = A[row][col] + B[row][col] and print by rows.
Find the maximum in every row
Use {{4,9,2},{7,1,8},{3,6,5}}. Find the maximum in each row separately and print 9 8 6.
- Use the outer loop to process rows.
- Initialize rowMax from the first element of each row.
- Compare remaining columns and print the maximum after each row.