Multi-dimensional arrays

Figure 462. Two-dimensional arrays Slide presentation
Code Result
// Allocation
final int[][] MATRIX = new int[2][3];

// Initialization
for (int row = 0; row < 2; row++) {
  for (int col = 0; col < 3; col++) {
    MATRIX[row][col] = col + row;
  }
}

// Output
for (int row = 0; row < 2; row++) {
  System.out.println(Arrays.toString(MATRIX[row]));         
}
[0, 1, 2]
[1, 2, 3]

Figure 463. Behind the scenes Slide presentation
final int[][] MATRIX = new int[2][]; // Array containing two int arrays
MATRIX[0] = new int[3];              // first int array
MATRIX[1] = new int[3];              // second int array

Conclusions:

  • Java only supports one-dimensional arrays.

  • By means of nesting we get the illusion of multi- dimensional arrays.


Figure 464. Memory allocation Slide presentation

exercise No. 155

2-dimensional arrays and .length

Q:

  1. In Figure 437, “Safer: Using length you were advised to favour .length over hard coded int values like e.g. 5: Replace the error prone limits 2 and 3 in Figure 462, “Two-dimensional arrays accordingly.

  2. Replace the second loop in Figure 462, “Two-dimensional arrays by a for-each style loop.

    Tip

    matrix[0] and matrix[1] are of type int[].

A:

Two-dimensional arrays in Java are nested arrays of arrays. We thus choose appropriate data types:

// Allocation
final int[][] MATRIX = new int[2][3];

// Initialization
for (int row = 0; row < MATRIX ; row++) {
  for (int col = 0; col < MATRIX[row].length ; col++) {
    MATRIX[row][col] = col + row;
  }
}

// Output
for (final int[]  row : MATRIX) {
  System.out.println(Arrays.toString(row));
}

The «outer» array's dimension: This int[][] array is the visible entry point containing references to rows each being implemented as a «simple» int[] array.

All rows are having identical length. We could thus use either representative matrix[0].length or matrix[1].length as well. However choosing matrix[row].length also works in case of different row lengths.

The variable matrix is of type int[][]. Each matrix[row] entry thus represents a reference to an «ordinary» int[] array. So row iteration requires a loop variable of type int[].

Figure 465. Nested array initialization Slide presentation
final int[][] MATRIX = new int[][] {
  {0, 1, 2},
  {1, 2, 3}
};

Figure 466. Nested »ragged« array initialization Slide presentation
Code Result
final String[][] GROUPS = new String[][] {
   {"Jill", "Tom"},
   {"Jane", "Smith", "Joe"},
   {"Jeff"}
};

for (final String[] GROUP: GROUPS) {
   System.out.println(Arrays.toString(GROUP));         
}
[Jill, Tom]
[Jane, Smith, Joe]
[Jeff]

exercise No. 156

Representing revenues by quarter and department

Q:

A CEO requires quarterly revenue reports for each of the company's three departments:

             |    Q1    Q2    Q3    Q4
-------------+------------------------
Department 1:| 17255 33198 32112 40213
Department 2:|  7629 13221  9226 10231
Department 3:| 34198 71926 25981 38912

Create a corresponding int[][] revenues = ... array for hosting the above values (just the numbers in red). Then add the required code for printing the above table.

Tip

If you actually favour colors like the above red text, you may want to read How to print color in console using System.out.println?.

A:

final int[][] revenues = {
        {17255, 33198, 32112, 40213}
       ,{ 7629, 13221,  9226, 10231}
       ,{34198, 71926, 25981, 38912}
};

System.out.println(
        """
                     |    Q1    Q2    Q3    Q4
        -------------+------------------------""");

final String ANSI_RESET = "\u001B[0m";  // Revert to regular.
final String ANSI_RED = "\u001B[31m";   // Print foreground red.

for (int department = 0; department < revenues.length; department++) {
    System.out.format(ANSI_RESET + "Department %d:|" + ANSI_RED, department + 1);
    for (final int revenue: revenues[department]) {
        System.out.format("%6d", revenue);
    }
    System.out.println();
}

exercise No. 157

External array and string exercises

Q:

Solve all examples from the following sections: