Lesson 14 of 34 · Arrays & ArrayList
Java 2D Arrays: Grids, Nested Loops and Sorting
Game boards, seating plans, spreadsheets and pixel images all have rows and columns. Java models them with 2D arrays — arrays whose elements are themselves arrays. In this lesson you will build grids, walk through them with nested loops and sort their rows.
Creating a 2D array
int[][] grid = new int[3][4]; // 3 rows, 4 columns, all 0
int[][] board = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(board[1][2]); // 6 → row 1, column 2
board[0][0] = 9;
The first index selects the row, the second the column — both start at 0. board.length is the number of rows (2) and board[0].length is the number of columns in row 0 (3).
Nested loops
To visit every cell, put one loop inside another: the outer loop walks the rows, the inner loop walks the columns of the current row.
int total = 0;
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
total += board[row][col];
}
}
With for-each, each element of board is a whole row of type int[]:
for (int[] row : board) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
9 2 3
4 5 6
To print the whole structure at once, use Arrays.deepToString(board), which gives [[9, 2, 3], [4, 5, 6]]. Plain Arrays.toString would only print the references of the inner arrays.
Jagged arrays
Because every row is its own array, rows can have different lengths:
int[][] triangle = {
{1},
{1, 1},
{1, 2, 1}
};
System.out.println(triangle[2].length); // 3
This is why the inner loop should use grid[row].length, never a fixed number or grid[0].length — code written that way works for rectangular and jagged grids alike.
Sorting with Arrays.sort
Arrays.sort puts an array's elements in ascending order — numbers from small to large, Strings alphabetically:
int[] loot = {40, 5, 23, 8};
Arrays.sort(loot);
System.out.println(Arrays.toString(loot)); // [5, 8, 23, 40]
String[] names = {"Mira", "Ash", "Tor"};
Arrays.sort(names);
System.out.println(Arrays.toString(names)); // [Ash, Mira, Tor]
Sorting changes the array in place. If you still need the original order, sort a copy made with Arrays.copyOf. A single row of a grid is an ordinary array, so Arrays.sort(grid[0]) sorts just that row.
Common mistakes
- Swapping the indexes:
grid[col][row]instead ofgrid[row][col]reads the wrong cell or goes out of bounds. - Using
grid.lengthfor columns: it is the number of rows. Columns aregrid[row].length. - Assuming every row has the same length: jagged arrays break code that hard-codes the width.
- Sorting the caller's data by accident:
Arrays.sort(grid[row])reorders the row inside the grid itself.
Assignment
Write four static methods in Main. Grids may be jagged unless stated otherwise:
sumAll(int[][] grid)— the total of every value; an empty grid gives0.rowSums(int[][] grid)— a new array where elementiis the sum of rowi(an empty row sums to0).columnSum(int[][] grid, int col)— the sum of columncolin a rectangular grid.sortedRow(int[][] grid, int row)— a sorted copy of the given row, in ascending order. The grid must not change.
int[][] grid = {{1, 2, 3}, {4, 5, 6}};
sumAll(grid) // 21
rowSums(grid) // [6, 15]
columnSum(new int[][]{{1, 2}, {3, 4}, {5, 6}}, 1) // 12
sortedRow(new int[][]{{9, 1, 5}, {3, 2}}, 0) // [1, 5, 9]Premium lesson
Unlock the full Learn Java course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.
Lesson last updated on .