2D Arrays

We can declare 2-dimensional arrays as follows.

int[][] m1 = new int[3][3];

Here m1 has 3 rows, each of length 3.  You can also declare a multi-dimensional array with rows of a length different than the number of columns.  Below m2 has 2 rows, each of length 3.

int[][] m2 = new int[2][3];

2D arrays are just arrays of arrays. So we can do the following.

m2[0] = new int[3];
m2[1] = new int[3];

You can also initialize a multi-dimensional array when it is declared.  Here is a 2D array whose rows are of different lengths.

int[][] matrix = {
    {1, 0, 0},
    {0, 1},

Iterating Over a 2D Array

We can iterate over the elements of a 2D array using nested for-loops.  If we don’t need to modify the values stored in the matrix, since 2D arrays are just arrays of arrays we can use for-each loops as shown below.

for (int[] arr:  matrix) {
    for (int elm : arr) {
        System.out.printf("%d ", elm);

If we need to modify the values stored in the matrix we can use a regular for-loop and iterate over the indices of the matrix.

for(int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        if (i == j) {
            matrix[i][j] = 1;

© 2017, Eric. All rights reserved.