Shiklo Programming
EN
  • English
  • Español
  • Português
  • Deutsch
  • Français
  • 日本語
  • हिन्दी

Java Multidimensional Arrays

Some data has rows and columns: a seating plan, a game board, the marks of several students in several subjects. Java stores such data in a two-dimensional array, which is simply an array whose elements are arrays.

Creating a 2D array

Write two pairs of square brackets. Each inner pair of curly brackets is one row:

public class Main {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6}
        };
        System.out.println(grid[0][2]);
        System.out.println(grid[1][0]);
        System.out.println("Rows: " + grid.length);
        System.out.println("Columns: " + grid[0].length);
    }
}
Output
3
4
Rows: 2
Columns: 3

grid[1][0] means row 1, column 0; both start at 0. grid.length is the number of rows and grid[0].length the number of columns in the first row.

Looping with nested loops

To visit every element, use a loop over the rows with a loop over the columns inside it, the nested loops you already know:

public class Main {
    public static void main(String[] args) {
        int[][] marks = {
            {78, 85, 90},
            {62, 70, 58},
            {95, 88, 92}
        };
        for (int row = 0; row < marks.length; row++) {
            int sum = 0;
            for (int col = 0; col < marks[row].length; col++) {
                System.out.print(marks[row][col] + " ");
                sum += marks[row][col];
            }
            System.out.println("| total " + sum);
        }
    }
}
Output
78 85 90 | total 253
62 70 58 | total 190
95 88 92 | total 275

An empty grid and deepToString

new int[3][4] makes 3 rows of 4 zeros. Arrays.deepToString prints a whole 2D array, where Arrays.toString from Arrays Class would only show codes for the rows:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        char[][] board = new char[3][3];
        for (char[] row : board) {
            Arrays.fill(row, '.');
        }
        board[1][1] = 'X';
        board[0][2] = 'O';
        System.out.println(Arrays.deepToString(board));
        for (char[] row : board) {
            System.out.println(new String(row));
        }
    }
}
Output
[[., ., O], [., X, .], [., ., .]]
..O
.X.
...

The for-each loop gives one row at a time, and each row is a char[] array that new String(row) turns into text.

Rows of different lengths

Because each row is its own array, rows can have different lengths. Such an array is called jagged:

public class Main {
    public static void main(String[] args) {
        int[][] triangle = new int[4][];
        for (int i = 0; i < triangle.length; i++) {
            triangle[i] = new int[i + 1];
            for (int j = 0; j <= i; j++) {
                triangle[i][j] = (j == 0 || j == i) ? 1 : triangle[i - 1][j - 1] + triangle[i - 1][j];
            }
        }
        for (int[] row : triangle) {
            for (int v : row) {
                System.out.print(v + " ");
            }
            System.out.println();
        }
    }
}
Output
1 
1 1 
1 2 1 
1 3 3 1 

This builds the first rows of Pascal's triangle, where each number is the sum of the two above it.

Practice exercises

  1. Store a 3 by 3 table of numbers and print the sum of each column.
  2. Print the numbers on the diagonal of a 4 by 4 array (grid[i][i]).
  3. Make a 5 by 5 multiplication table in a 2D array and print it neatly with printf.