Multi-dimensional arrays

Figure 209. 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++) {
  IO.println(Arrays.toString(MATRIX[row]));         
}
[0, 1, 2]
[1, 2, 3]

Figure 210. 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 211. Memory allocation Slide presentation

exercise No. 95

2-dimensional arrays and .length

Q:

  1. In Figure 202, “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 209, “Two-dimensional arrays accordingly.

  2. Replace the second loop in Figure 209, “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) {
  IO.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 212. Nested array initialization Slide presentation
final int[][] MATRIX = new int[][] {
  {0, 1, 2},
  {1, 2, 3}
};

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

for (final String[] GROUP: GROUPS) {
   IO.print('[');
   for (final String s: GROUP) {
      IO.print(s + ' ');
   }
   IO.println(']');
}
[Jill Tom ]
[Jane Smith Joe ]
[Jeff ]

exercise No. 96

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 IO.println.

A:

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

IO.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);
    }
    IO.println();
}

exercise No. 97

Summing up revenues

Q:

Extend the previous exercise by adding quarterly revenue sums per department:

            |     Q1     Q2     Q3     Q4
------------+----------------------------
Department 1|  17255  33198  32112  40213
Department 2|   7629  13221   9226  10231
Department 3|  34198  71926  25981  38912
------------+----------------------------
         Sum|  59082 118345  67319  89356

A:

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

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

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


final int[] quarterlySums = new int[4];
for (int department = 0; department < revenues.length; department++) {
    System.out.format(ANSI_RESET + "Department %d|" + ANSI_RED, department + 1);
    for (int quarter = 0; quarter < revenues[department].length; quarter++) {
        quarterlySums[quarter] += revenues[department][quarter];
        System.out.format("%7d", revenues[department][quarter]);
    }
    IO.println();
}
IO.print( ANSI_RESET +
        """
        ------------+----------------------------
                 Sum|""");
for (final int sum: quarterlySums) {
    System.out.format("%7d", sum);
}

exercise No. 98

External array and string exercises

Q:

Try solving as many examples as possible from the following sections: