2D Arrays

A 2 dimensional array can be thought of in two ways: either as a table with rows and columns or as an array of arrays. In other words, an array in which each cell holds another array. Visually, we often think of the former, but Java actually implements 2D arrays as the latter.

Declaring 2D Arrays

2D arrays are declared the same way that 1D arrays are, except the declaration needs two sets of square brackets. For example, int table[] [] = new int[4][5]. This creates a 2D array of ints with 4 rows and 5 columns. Counting, similar to 1D arrays, starts at 0, so to access the second row, third column, we would type table[1][2].

Initializing arrays with predetermined values can be accomplished at the time of declaration. The following statement is valid:
int[ ][ ] table = { {0, 1, 2, 3, 4, }, {10, 11, 12, 13, 14}, {20, 21, 22, 23, 24}, {30, 31, 32, 33, 34} };

Traversing 2D Arrays

In working with 2D arrays, the most efficient way to cycle through the information is a nested for loop structure, with the outer loop changing rows and the inner loop changing columns. For example:
for(int r=0; r<4; r++) for(int c=0; c<5; c++) table[r][c] = reader.readInt(“Enter a number”);
As previously mentioned, Java looks at 2D array as an array of arrays. So, when utilizing the .length property from a 2D array variable, we actually see the number of rows. To get the number of columns, we need to call the length property from one of the rows(EX: table[0].length). This view of arrays does, however, allow us to create rugged arrays, or arrays in which each row has a different number of columns. Often, rugged arrays are considered bad practice, I only mention them for information. So a generic form of a 2D array traversal, where the size may not be known, would look like this:
for(int r=0; r<table.length; r++) for(int c=0; c<table[r].length; c++) table[r][c] = reader.readInt(“Enter a number”);

Arrays as Parameters

We can send an entire array into a method either for information or for alteration. BE CAREFUL - arrays are reference type variables and altering an array in a method will also alter it in the caller. If you want to make temporary changes using the array data in a method, copy the array into a temporary array that can be altered.

When sending an array as a parameter, we simply write the array name in the method call. So, if we are calling a method sortStudents that takes the array and number of students, the call would look like this:
sortStudents(students, numStudents); //students is a previously declared array
The method header needs to know that is expecting a 2D array of strings and an integer, so it would look like this: public static void sortStudents(String [][] s, int num)