Java multidimensional arrays are arrays of arrays. For instance, a two-dimensional array is an array of arrays. A three-dimensional array is an array of arrays of arrays, etc. In general, when the elements of an array are themselves arrays, the array is said to be multidimensional. Everything you already know about single-dimensional arrays applies to multidimensional arrays. This means you are already over half way to complete mastery of multidimensional arrays. All you need to know now is how to declare them and use them in your programs.
You can declare arrays of just about any dimension. However, the most common multidimensional arrays you will see in use are of two or three dimensions. The syntax for declaring and creating a two-dimensional array is shown in figure 8-18.
Figure 8-18: Array Declaration Syntax for a Two-Dimensional Array
As figure 8-18 illustrates there are a few new things to keep in mind when declaring multidimensional arrays. First, you will include an extra set of brackets for each additional dimension you want to give your array. Since this is an example of a two-dimensional array there is one extra set of brackets appended to the array type.
When you use the new operator to allocate memory for the array, only the leftmost dimension(s) are mandatory while the rightmost dimension is optional. This enables you to create jagged arrays. (i.e., arrays of different lengths)
Let’s take a look at an example of a multidimensional array declaration. The following line of code declares and creates a two-dimensional array of integers with the dimensions 10 by 10:
int[][] int_2d_array = new int[10][10];
You could think of this array as being arranged by rows and columns as is shown in figure 8-19.
Figure 8-19: A Two Dimensional Array with Dimensions 10 by 10
Each row is a reference to an integer array and there are 10 rows (int[10][]) and each column is an element of a 10 integer array (int[10][10]). Each element of int_2d_array can be accessed using a double set of brackets that indicate the row and column of the desired element. For example, the 3rd element of the 3rd array can be found at int_2d_array[2][2], the 1st element of the 6th array can be found at int_2d_array[5][0], the 6th element of the 6th array can be found at int_2d_array[5][5], and the 9th element of the 10th array can be found at int_2d_array[9][8].
Example 8.9 is a short program that will let you experiment with creating two dimensional arrays of different dimensions. Figure 8-20 shows this program in action using arrays of various dimensions.
Example 8.9: MultiArrays.java
1 public class MultiArrays { 2 public static void main(String[] args){ 3 int rows = Integer.parseInt(args[0]); 4 int cols = Integer.parseInt(args[1]); 5 6 int[][] int_2d_array = new int[rows][cols]; 7 8 System.out.println(int_2d_array.getClass()); 9 10 for(int i = 0; i<int_2d_array.length; i++){ 11 for(int j = 0; j<int_2d_array[i].length; j++){ 12 System.out.print(int_2d_array[i][j]); 13 } 14 System.out.println(); 15 } 16 } 17 }
Figure 8-20: Results of Running Example 8.9
Referring to example 8.9 — the getClass() method is used on line 8 to determine int_2d_array’s class type. As you can see from figure 8-20 its class type is “[[I” meaning array of int arrays. When this program is run the number of rows desired is entered on the command line followed by the number of columns desired. It simply creates an integer array with the desired dimensions and prints its contents to the console in row order.
Figure 8-21 offers a memory representation of the int_2d_array used in example 8.9 with the dimensions of 2 rows and 10 columns. As you can see, the int_2d_array reference declared in the main() method points to an array of integer arrays. This array of integer arrays represents the rows. Each “row” element is a reference to an array of integers. The length of each of these integer arrays represents the number of columns contained in the two-dimensional array.
Figure 8-21: Memory Representation of int_2d_array with 2 Rows and 10 Columns
Multidimensional arrays can be created using array literals. Example 8.10 is a short program that creates several two-dimensional arrays using array literal values. Figure 8-22 shows the results of running this program.
Example 8.10: TwoDArrayLiterals.java
1 public class TwoDArrayLiterals { 2 public static void main(String[] args){ 3 /************** ragged int array **************************/ 4 int[][] int_2d_ragged_array = {{1,2}, 5 {1,2,3,4}, 6 {1,2,3}, 7 {1,2,3,4,5,6,7,8}}; 8 9 10 for(int i = 0; i < int_2d_ragged_array.length; i++){ 11 for(int j = 0; j < int_2d_ragged_array[i].length; j++){ 12 System.out.print(int_2d_ragged_array[i][j] + " "); 13 } 14 System.out.println(); 15 } 16 17 /************* ragged String array ***********************/ 18 String[][] string_2d_ragged_array = {{"Now ", "is ", "the ", "time "}, 19 {"for ", "all ", "good men "}, 20 {"to come to ", "the aid "}, 21 {"of their country!"}}; 22 23 for(int i = 0; i < string_2d_ragged_array.length; i++){ 24 for(int j = 0; j < string_2d_ragged_array[i].length; j++){ 25 System.out.print(string_2d_ragged_array[i][j]); 26 } 27 System.out.println(); 28 } 29 } 30 }
Figure 8-22: Results of Running Example 8.10
The arrays created in example 8.10 are known as ragged arrays. A ragged array is a multidimensional array having row lengths of varying sizes. Ragged arrays are easily created using array literals. That’s because each row dimension can be explicitly set when the array is declared and created at the same time.
Another way to create a ragged array is to omit the final dimension at the time the array is created, and then dynamically create each array of the final dimension. Study the code shown in example 8.11.
Example 8.11: RaggedArray.java
1 import java.io.*; 2 3 public class RaggedArray { 4 public static void main(String[] args){ 5 BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); 6 int[][] int_2d_ragged_array = new int[5][]; //rightmost dimension omitted 7 int dimension = 0; 8 9 /**************** get dimension of each ragged array ****************/ 10 for(int i = 0; i < int_2d_ragged_array.length; i++){ 11 System.out.print("Enter the ragged array dimension: "); 12 dimension = 0; 13 try { 14 dimension = Integer.parseInt(console.readLine()); 15 }catch(NumberFormatException nfe){ System.out.println("Bad number! Dimension being set to 3"); 16 dimension = 3; } 17 catch(IOException ioe){ System.out.println("Problem reading console! Dimension being set to 3"); 18 dimension = 3; } 19 20 int_2d_ragged_array[i] = new int[dimension]; 21 }//end for 22 23 /******************** print contents of array *********************/ 24 for(int i = 0; i < int_2d_ragged_array.length; i++){ 25 for(int j = 0; j < int_2d_ragged_array[i].length; j++){ 26 System.out.print(int_2d_ragged_array[i][j]); 27 } // end inner for 28 System.out.println(); 29 }//end outer for 30 31 }//end main 32 }//end class
Figure 8-23: Results of Running Example 8.11
The important point to note about example 8.11 occurs on line 6. Notice how the rightmost array dimension is omitted when the array is created with the new operator. Since the final array dimension is missing, the length of each final array must be explicitly created in the program. This is done in the first for loop that begins on line 10. Each final array is actually created on line 20.
The example presented in this section shows how single- and multidimensional arrays can be used together to achieve a high degree of functionality.
Example 8.12 gives the code for a class named WeightedGradeTool. The program calculates a student’s final grade based on weighted grades. Figure 8-24 shows the results of running this program.
Example 8.12: WeightedGradeTool.java
1 import java.io.*; 2 3 public class WeightedGradeTool { 4 public static void main(String[] args){ 5 BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); 6 double[][] grades = null; 7 double[] weights = null; 8 String[] students = null; 9 int student_count = 0; 10 int grade_count = 0; 11 double final_grade = 0; 12 13 System.out.println("Welcome to Weighted Grade Tool"); 14 15 /**************** get student count *********************/ 16 System.out.print("Please enter the number of students: "); 17 try{ 18 student_count = Integer.parseInt(console.readLine()); 19 }catch(NumberFormatException nfe){ System.out.println("That was not an integer!"); 20 System.out.println("Student count will be set to 3."); 21 student_count = 3; } 22 catch(IOException ioe){ System.out.println("Trouble reading from the console!"); 23 System.out.println("Student count will be set to 3."); 24 student_count = 3; } 25 26 if(student_count > 0){ 27 students = new String[student_count]; 28 /***************** get student names **********************/ 29 getNames: for(int i = 0; i < students.length; i++){ 30 System.out.print("Enter student name: "); 31 try{ 32 students[i] = console.readLine(); 33 } catch(IOException ioe){ System.out.println("Problem reading console!"); 34 System.exit(0); } 35 }//end getNames for 36 37 /**************** get number of grades per student ****************************/ 38 System.out.print("Please enter the number of grades to average: "); 39 try{ 40 grade_count = Integer.parseInt(console.readLine()); 41 }catch(NumberFormatException nfe){ System.out.println("That was not an integer!"); 42 System.out.println("Grade count will be set to 3."); 43 grade_count = 3; } 44 catch(IOException ioe){ System.out.println("Trouble reading from the console!"); 45 System.out.println("Grade count will be set to 3."); 46 grade_count = 3; } 47 48 /****************** get raw grades *****************************/ 49 grades = new double[student_count][grade_count]; 50 getGrades: for(int i = 0; i < grades.length; i++){ 51 System.out.println("Enter raw grades for " + students[i]); 52 for(int j = 0; j < grades[i].length; j++){ 53 System.out.print("Grade " + (j+1) + ": "); 54 try{ 55 grades[i][j] = Double.parseDouble(console.readLine()); 56 }catch(NumberFormatException nfe){ System.out.println("That was not a double!"); 57 System.out.println("Grade will be set to 100"); 58 grades[i][j] = 100; } 59 catch(IOException ioe){ System.out.println("Trouble reading from the console!"); 60 System.out.println("Grade will be set to 100."); 61 grades[i][j] = 100; } 62 63 }//end inner for 64 }// end getGrades for 65 66 /***************** get grade weights *********************/ 67 weights = new double[grade_count]; 68 System.out.println("Enter grade weights. Make sure they total 100%"); 69 getWeights: for(int i = 0; i < weights.length; i++){ 70 System.out.print("Weight for grade " + (i + 1) + ": "); 71 try{ 72 weights[i] = Double.parseDouble(console.readLine()); 73 }catch(NumberFormatException nfe){ System.out.println("That was not a double!"); 74 System.out.println("Program will exit!"); 75 System.exit(0); } 76 catch(IOException ioe){ System.out.println("Trouble reading from the console!"); 77 System.out.println("Program will exit!"); 78 System.exit(0); } 79 }//end getWeights for 80 81 /****************** calculate weighted grades ********************/ 82 calculateGrades: for(int i = 0; i < grades.length; i++){ 83 for(int j = 0; j < grades[i].length; j++){ 84 grades[i][j] *= weights[j]; 85 }//end inner for 86 }//end calculateGrades for 87 88 /***************** calculate and print final grade *********************/ 89 finalGrades: for(int i = 0; i < grades.length; i++){ 90 System.out.println("Weighted grades for " + students[i] + ": "); 91 final_grade = 0; 92 for(int j = 0; j < grades[i].length; j++){ 93 final_grade += grades[i][j]; 94 System.out.print(grades[i][j] + " "); 95 }//end inner for 96 System.out.println(students[i] +"'s final grade is: " + final_grade ); 97 }//end averageGrades for 98 }// end if 99 }// end main 100 }// end class
Figure 8-24: Results of Running Example 8.12
Multidimensional arrays are arrays having more than one dimension. Multidimensional arrays in Java are arrays of arrays. An understanding of single-dimensional Java arrays leads to quick mastery of multidimensional arrays.
To declare a multidimensional array simply add a set of brackets to the array element type for each dimension required in the array. Multidimensional arrays can contain any number of dimensions, however, arrays of two and three dimensions are most common.
Multidimensional arrays can be created using array literal values. The use of array literals enables the initialization of each array element at the point of declaration.
Ragged arrays are multidimensional arrays having final element arrays of various lengths. Ragged arrays can be easily created with array literals. They can also be created by omitting the final dimension at the time of array creation and then dynamically creating each final array with a unique length.