Example project

Suggested reading: sections 8.2-8.6, 8.8

Multi-dimesional arrays

An ordinary array in Java is also referred to as a one-dimensional array. The code to create a one-dimensional array looks like

int A[] = new int[100];

An ordinary array stores a list of simple data items.

A multi-dimensional array is a list of lists. Here is some Java code to create a two-dimensional array.

int A[][] = new int[100][10];

In this example the array A is a list of 100 items, where each item itself is a list of 10 data items.

Working with multidimensional arrays

The most common example of a multi-dimensional array is a 2 dimensional array. The simplest way to visualize a 2-d array is as a table of rows and columns. The first index in the array gives the row number, and the second index gives the column number.

Filling a 2-d array with data is most commonly done with a pair of nested loops. The outer loop iterates over the rows of the grid, and the inner loop iterates over the columns of the grid.

Here is an example that fills in a 2-d grid with a multiplication table.

int T[][] = new int[10][10];

for(int row = 0;row < 10;row++) {
  for(int col = 0;col < 10;col++) {
    T[row][col] = (row+1)*(col+1);
  }
}

Three examples

At the top of these notes you will find a button that links to an archive containing a NetBeans project with three example programs in it. These examples are all based on examples from chapter 8 in the textbook.

Other than modifying these programs to read data from a file, the code I have provided is very similar to the code in the textbook in chapter 8. I refer you to the discussions of these examples in the chapter for more details.