Java Multidimensional Arrays

A multidimensional array is an array of arrays. The most common is the two dimensional (2D) array, like a table with rows and columns.

Create a 2D array

public class Main {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        System.out.println(matrix[0][0]);      // row 0, column 0
        System.out.println(matrix[1][2]);      // row 1, column 2
        System.out.println(matrix.length);     // number of rows
        System.out.println(matrix[0].length);  // number of columns
    }
}
Output

1
6
3
3

Loop with nested loops

public class Loop {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }

        int sum = 0;
        for (int[] row : matrix) {
            for (int value : row) {
                sum += value;
            }
        }
        System.out.println("Sum: " + sum);
    }
}
Output

1 2 3
4 5 6
7 8 9
Sum: 45

Create an empty 2D array

import java.util.Arrays;

public class Empty {
    public static void main(String[] args) {
        int[][] grid = new int[2][4];       // 2 rows, 4 columns, all 0
        grid[1][2] = 7;
        System.out.println(Arrays.deepToString(grid));
    }
}
Output

[[0, 0, 0, 0], [0, 0, 7, 0]]

Arrays.deepToString() prints a 2D array in one line.

Jagged arrays

The rows can have different lengths:

import java.util.Arrays;

public class Jagged {
    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];
            Arrays.fill(triangle[i], i + 1);
        }
        for (int[] row : triangle) {
            System.out.println(Arrays.toString(row));
        }
    }
}
Output

[1]
[2, 2]
[3, 3, 3]
[4, 4, 4, 4]

Example: matrix addition

import java.util.Arrays;

public class Add {
    public static void main(String[] args) {
        int[][] a = {{1, 2}, {3, 4}};
        int[][] b = {{5, 6}, {7, 8}};
        int[][] c = new int[2][2];

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                c[i][j] = a[i][j] + b[i][j];
            }
        }
        System.out.println(Arrays.deepToString(c));
    }
}
Output

[[6, 8], [10, 12]]

Note: A 2D array is really an array whose items are arrays. That is why every row can have its own length. Next: Java Methods.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.