Chapter 11: Multidimensional Arrays
Part 11 of 17 in Intro to Java SeriesNext: Chapter 12: Advanced String Concepts →

This chapter expands on the knowledge discussed about arrays in Chapter 9. You will learn about multidimensional arrays, starting with two-dimensional arrays.
The arrays and ArrayLists in the previous two chapters were all one-dimensional arrays. You can think of them like a linear structure of data, where each element in the array comes directly after the element before it.
Multidimensional arrays are arrays that occupy over one dimension. The simplest multidimensional array is a two-dimensional (2D) array. You could think of this like a table, with rows and columns, instead of just one single line.
1D/2D Array Visualization
Image: Kevin Olson · CC BY-NC-SA
2D Arrays
A two-dimensional array is a data structure with two dimensions. You can think of it as a table with rows and columns. Keep in mind that data structures are abstract computer concepts. Your computer does not implicitly know what part of the index represents a "row" or the "column." How you structure your array is entirely up to you.
2D arrays are created much like 1D arrays. The difference is the amount of indices defined.
1//creating a 1D array
2int[] myArray = new int[6];
3
4//creating a 2D array 6x4 (total 24 values)
5int[][] myBiggerArray = new int[6][4];
In the example below, a 3x2 array is created. The first index can be thought of as the row in the table, where each row is a different student. The second index is the column - the first column being the student's ID number and the second column being their grade. There are 3 rows of students in this array, and 2 columns, so it's a 3x2 array with a total of six int values.
1public static void main(String[] args) {
2
3 //a new three by two array
4 int[][] studentGrades = new int[3][2];
5
6 //the first index for each student, the second for the different values associated with them (id and grade)
7 studentGrades[0][0] = 432;
8 studentGrades[0][1] = 92;
9 studentGrades[1][0] = 433;
10 studentGrades[1][1] = 75;
11 studentGrades[2][0] = 435;
12 studentGrades[2][1] = 88;
13
14 //print out the student ids and their grades
15 for(int i = 0; i < 3; i++){
16 System.out.println("The student with ID number: " + studentGrades[i][0] + " has a grade of " + studentGrades[i][1] + "%");
17 }
18
19}
The student with ID number: 432 has a grade of 92% The student with ID number: 433 has a grade of 75% The student with ID number: 435 has a grade of 88%
Extra Grades
Now, let's examine a situation in which we want to add multiple grades to the array, rather than just one. The first column will remain the student's id, the second their English grade, followed by their Math and Science grades.
There is no need to create a three-dimensional array. We are just adding more columns to the existing 2D array.
The same three students will be kept from the previous example. So we need to create a 3x4 array,
1//a new three by four
2int[][] studentGrades = new int[3][4];
3
4//the first index can hold the student's id number, the second, their grade.
5studentGrades[0][0] = 432;
6studentGrades[0][1] = 92;
7studentGrades[0][2] = 87;
8studentGrades[0][3] = 97;
9studentGrades[1][0] = 433;
10studentGrades[1][1] = 75;
11studentGrades[1][2] = 80;
12studentGrades[1][3] = 96;
13studentGrades[2][0] = 435;
14studentGrades[2][1] = 88;
15studentGrades[2][2] = 92;
16studentGrades[2][3] = 69;
17
18//print out the student ids and their grades
19for(int i = 0; i < 3; i++){
20 System.out.println("The student with ID number: " + studentGrades[i][0] + " has a grade of " + studentGrades[i][1] + "% in English, " + studentGrades[i][2] + "% in Math, " + studentGrades[i][3] + "% in Science.");
21}
The student with ID number: 432 has a grade of 92% in English, 87% in Math, 97% in Science. The student with ID number: 433 has a grade of 75% in English, 80% in Math, 96% in Science. The student with ID number: 435 has a grade of 88% in English, 92% in Math, 69% in Science.
.length
Using .length returns the static value holding the length of an array. In the above example, it will return 3, as that is the length of the first dimension of the array. To get the length of the second dimension, you need to add a blank [0] to the reference variable. In the 3x4 array, studentGrades.length returns 3, and studentGrades[0].length returns 4.
Sample Problem
Directions: Using the 3x4 array from the above extra grades section (you may just copy/paste it into a project), create an algorithm that finds each student's average grade across all three subjects, and prints it to the screen. Do this using an outer loop which iterates through the students, and an inner loop that iterates through the grades.
Sample Output:
1Student with id: 432 has an average grade of: 92.0%
2Student with id: 433 has an average grade of: 83.66666666666667%
3Student with id: 435 has an average grade of: 83.0%
Sample Solution
1//iterate through each student
2for(int i = 0; i < studentGrades.length; i++){
3 double average = 0;
4 //find sum of their grades
5 for(int x = 1; x< studentGrades[0].length; x++){
6 average += studentGrades[i][x];
7 }
8 //find and print average
9 average = average / 3;
10 System.out.println("Student with id: " + studentGrades[i][0] + " has an average grade of: " + average + "%");
11}
Shorthand Syntax
Recall that a 1D array can be declared, initialized, and populated with values using this shorthand syntax:
1int[] myArray = {5, 10, 15, 20, 25};
The same can be done with 2D arrays. In this example, a 2x3 array is created using shorthand syntax.
1int[][] anotherArray = {{5,10,15},{10,20,30}};
The outer part of the array {A,B} is the first dimension of the array. The inner part {{x,y,z},{x,y,z}} is the second dimension.
1//this array is functionally equivalent
2int[][] anotherArray = {{5,10,15},{10,20,30}};
3
4//to this array
5int[][] anArray = new int[2][3];
6anArray[0][0] = 5;
7anArray[0][1] = 10;
8anArray[0][2] = 15;
9anArray[1][0] = 10;
10anArray[1][1] = 20;
11anArray[1][2] = 30;
Another way to format the 2D array with shorthand is to separate the first dimension of elements by line, and the second element into rows. This way may be more visually pleasing and easy to understand.
1int[][] anotherArray = {
2 {5,10,15},
3 {10,20,30}
4};
Table Printer Assignment
Instructions: Look at the table of Strings below. Take the information in the table cells, place them in an array, and print the table to the screen in a nicely formatted manner. Use vertical bars | to create the edges of the cells.
Define the array in the main method, then print the array using a separate method. A basic template is provided below.
To keep each column the same width, you may add spaces to the end of the strings, so each string in the column has the same width of characters.
Sample Output:
|Name |Fav Color|Fav Food|Fav Place| |Jack |Violet |Tacos |Beach | |Sammy|Black |Sushi |New York | |Joey |Green |Steak |Japan |
Starting Code
Here is some code to help you get started.
1public class Main {
2 public static void main(String[] args) {
3
4 //Create the Array
5 String studentData[][] = {
6 //data here
7 };
8
9 tablePrinter(studentData);
10
11 }
12
13 /**
14 * @param arr The array being printed to the screen in a nicely formatted manner
15 */
16 public static void tablePrinter(String[][] arr) {
17
18
19 }
20
21}
Solution
1import java.util.ArrayList;
2import java.util.Collections;
3
4public class Main {
5 public static void main(String[] args) {
6
7 //Create the Array
8 String studentData[][] = {
9 {"Name ", "Fav Color", "Fav Food", "Fav Place"},
10 {"Jack ", "Violet ", "Tacos ", "Beach "},
11 {"Sammy", "Black ", "Sushi ", "New York "},
12 {"Joey ", "Green ", "Steak ", "Japan "}
13 };
14
15 tablePrinter(studentData);
16
17 }
18
19 /**
20 * @param arr The array being printed to the screen in a nicely formatted manner
21 */
22 public static void tablePrinter(String[][] arr) {
23 //iterate through the rows
24 for (int row = 0; row < arr.length; row++) {
25 //print the first vertical bar
26 System.out.print("|");
27 //iterate through the columns
28 for (int col = 0; col < arr[0].length; col++) {
29 //print the contents of each column, followed by a vertical bar
30 System.out.print(arr[row][col]);
31 System.out.print("|");
32 }
33 System.out.println();
34 }
35 }
36
37}
3D Arrays
Adding a third dimension to an array works the same way as a 2D array. Visually, you can think of a 3D array like a cube.
In the illustration, the first index is the plane or depth of the array, the second is the row, and the third is the column.
Creating a 3D array is the same as a 1D or 2D array, with the extra brackets for the extra indices.
1//a 3x4x4 array
2int[][][] array = new int [3][4][4];
Yearly Gradebook Example
Below is a 3D array created with shorthand syntax. It contains the grades of 3 senior students, in four different subjects, across the past 4 years. So the three dimensions are year, student, and subject.
1int grades[][][] = {
2 //year zero
3 { //student 0 student 1 student 2
4 {89,95,85,93},{99,82,95,90},{91,87,90,77}
5 },
6 //year one
7 { //student 0 student 1 student 2
8 {90,90,88,90},{92,87,86,89},{95,95,90,87}
9 },
10 //year two
11 { //student 0 student 1 student 2
12 {90,80,90,75},{85,81,79,81},{99,98,90,89}
13 },
14 //year three
15 { //student 0 student 1 student 2
16 {92,82,81,78},{89,81,74,85},{97,85,89,90}
17 }
18};
The way it's setup, the first index is the year from 0 to 3, where 0 is the current year and 3 is 3 years ago. The second index is the student, numbered 0 through 2, for a total of 3 students. The third index is the subject, 0 for Math, 1 for English, 2 Science, and 3 History. The array may be used to access the grades of any of the three students in any of the four subjects across the past four years.
1System.out.println("Second student's grade in English from 3 years ago:");
2System.out.println(grades[3][1][1]);
3
4System.out.println("First student's grade in Math from this year:");
5System.out.println(grades[0][0][0]);
Chapter Assignment: Gradebook
Instructions: Create a simple Gradebook program. The program will contain a 2D array of Strings. It will be 50x5, so 50 rows and 5 columns. Each row will correspond to the student's ID, starting with zero (so do not create a separate column to store an arbitrary ID). Since there are 50 rows, it supports a maximum of 50 students. Column zero will be their name, 1 will be Math grade, 2 is English grade, 3 is Science grade, and 4 is History grade.
The program will have the following capabilities:
- List all students and their grades from the Gradebook
- Add a new student, with their name and grade in each subject
- Modify an existing student based on their ID number, updating their name and grades.
- Calculate the GPA of the student's four grades, as an average.
Assumptions: When entering data, we can assume that the user always types the correct value. There is no need to do extensive error checking or "idiot proofing". The gradeBook may use public/static variables to keep track of student grades, and the number of students in the book. These are not the best practices, but we want to get a functioning gradebook, illustrating that you understand 2D array concepts.
The grades will be stored in String format, so our grade book can contain both student names and their grades. You may convert the grades back to double format by using the following method:
The program will not save any data locally once the program terminates.
1//Convert String to Double
2double aDouble = Double.valueOf(STRING);
Starter Code
1import java.util.Scanner;
2
3public class Main {
4
5 //the gradeBook array will be 50x5, supporting up to 50 students with their name, english, math, science, and history grades (in that order).
6 static String[][] gradeBook = new String[50][5];
7
8 //keep track of total number of students in the system
9 static int numStudents = 0;
10
11 //For reading user input later in the program
12 static Scanner userInput = new Scanner(System.in);
13
14 public static void main(String[] args) {
15
16 System.out.println("Welcome to Gradebook.");
17
18 //Make the decision(s)
19 makeDecision();
20
21 System.out.println("Program terminating. All data is lost.");
22 userInput.close();
23
24 }
25
26 /**
27 * Allows the user to select what to do next
28 */
29 public static void makeDecision() {
30
31 System.out.println("\nPlease select an option.");
32 System.out.println("0) Exit the program.");
33 System.out.println("1) List all students and grades");
34 System.out.println("2) Add new student and grades");
35 System.out.println("3) Modify individual student");
36 System.out.println("4) Calculate individual student GPA.");
37
38 int selection = userInput.nextInt();
39
40 if (selection == 0) {
41 return;
42 } else if (selection == 1) {
43 listAllGrades();
44 } else if (selection == 2) {
45 addNew();
46 }
47 else if (selection == 3) {
48 modifyStudent();
49 }
50
51 else if (selection == 4){
52 calcGPA();
53 }
54 else{
55 System.out.println("Invalid selection entered.");
56 makeDecision();
57 }
58
59 }
60
61 /**
62 * List all the recorded grades in the gradeBook
63 */
64 public static void listAllGrades() {
65 System.out.println("-- Student Grades Report --");
66
67 //TODO Iterate through the grades in the gradebook, printing their result by calling the printStudent method.
68
69
70 //Go back to makeDecision
71 makeDecision();
72
73
74 }
75
76 /**
77 * Add a new student to the book, as a new row in the "table"
78 */
79 public static void addNew(){
80
81
82 //TODO - Add code using Scanner to record the next student's information into the Array
83 //The first index of gradeBook array should be [numStudents], this is the NEXT row being added to the array.
84 //Increment numStudents by 1 when done, so the next index comes after this one
85
86 //Go back to makeDecision
87 makeDecision();
88
89 }
90
91 /**
92 * Modify an existing student given their ID
93 */
94 public static void modifyStudent(){
95 System.out.println("-- Modify Student --");
96 System.out.println("Enter Student ID: ");
97
98 //TODO: Get the student's ID using scanner
99
100 //TODO: Modify the student's information (Have them re-enter all 5 values)
101
102 makeDecision();
103
104 }
105
106 /**
107 * Print out a student's information
108 * @param studentID - The ID of the student being printed
109 */
110 public static void printStudent(int studentID){
111
112 //TODO: Print out the student's details in a nicely formatted String
113
114 }
115
116 /**
117 * Calculate the student's GPA by adding all 4 grades together, and dividing by 4.
118 * You may use Double.valueOf(STRING) to get the double value of a String.
119 */
120 public static void calcGPA(){
121 System.out.println("Enter the student's ID:");
122
123 //TODO: Get the student ID entered
124 //Calculate the GPA. Print out the student's name and their GPA.
125
126 makeDecision();
127
128 }
129
130}
Sample Output
Welcome to Gradebook. Please select an option. 0) Exit the program. 1) List all students and grades 2) Add new student and grades 3) Modify individual student 4) Calculate individual student GPA. 2 -- Add a new student -- What is their name? Kevin What is their Math grade? 87 What is their English grade? 79 What is their Science grade? 98 What is their History grade? 78 Student added with these properties: ID: 0 Name: Kevin Grades - Math: [87] English: [79] Science: [98] History: [78] Please select an option. 0) Exit the program. 1) List all students and grades 2) Add new student and grades 3) Modify individual student 4) Calculate individual student GPA. 3 -- Modify Student -- Enter Student ID: 0 Modifying Kevin Enter new name: Kevin Enter new Math grade? 65 Enter new English grade? 76 Enter new Science grade? 87 Enter new History grade? 97 Student has been updated with these details: ID: 0 Name: Kevin Grades - Math: [65] English: [76] Science: [87] History: [97] Please select an option. 0) Exit the program. 1) List all students and grades 2) Add new student and grades 3) Modify individual student 4) Calculate individual student GPA. 4 Enter the student's ID: 0 Kevin has a GPA of 81.250000 Please select an option. 0) Exit the program. 1) List all students and grades 2) Add new student and grades 3) Modify individual student 4) Calculate individual student GPA. 2 -- Add a new student -- What is their name? Jackie What is their Math grade? 76 What is their English grade? 87 What is their Science grade? 68 What is their History grade? 98 Student added with these properties: ID: 1 Name: Jackie Grades - Math: [76] English: [87] Science: [68] History: [98] Please select an option. 0) Exit the program. 1) List all students and grades 2) Add new student and grades 3) Modify individual student 4) Calculate individual student GPA. 0 Program terminating. All data is lost. Process finished with exit code 0
Complete Solution
1import java.util.Scanner;
2
3public class Main {
4
5 //the gradeBook array will be 50x5, supporting up to 50 students with their name, english, math, science, and history grades (in that order).
6 static String[][] gradeBook = new String[50][5];
7
8 //keep track of total number of students in the system
9 static int numStudents = 0;
10
11 //For reading user input later in the program
12 static Scanner userInput = new Scanner(System.in);
13
14 public static void main(String[] args) {
15
16 System.out.println("Welcome to Gradebook.");
17
18 //Make the decision(s)
19 makeDecision();
20
21 System.out.println("Program terminating. All data is lost.");
22 userInput.close();
23
24 }
25
26 /**
27 * Allows the user to select what to do next
28 */
29 public static void makeDecision() {
30
31 System.out.println("\nPlease select an option.");
32 System.out.println("0) Exit the program.");
33 System.out.println("1) List all students and grades");
34 System.out.println("2) Add new student and grades");
35 System.out.println("3) Modify individual student");
36 System.out.println("4) Calculate individual student GPA.");
37
38
39 int selection = userInput.nextInt();
40
41 if (selection == 0) {
42 return;
43 } else if (selection == 1) {
44 listAllGrades();
45 } else if (selection == 2) {
46 addNew();
47 }
48 else if (selection == 3) {
49 modifyStudent();
50 }
51
52 else if (selection == 4){
53 calcGPA();
54 }
55 else{
56 System.out.println("Invalid selection entered.");
57 makeDecision();
58 }
59
60 }
61
62 /**
63 * List all the recorded grades in the gradeBook
64 */
65 public static void listAllGrades() {
66 System.out.println("-- Student Grades Report --");
67
68 if( numStudents == 0){
69 System.out.println("There are no students in the database. Please add them.");
70 }
71 else{
72 //loop through students and print them out
73 for(int i = 0; i < numStudents; i++){
74 printStudent(i);
75 }
76
77 }
78 makeDecision();
79
80
81 }
82
83 /**
84 * Add a new student to the book, as a new row in the "table"
85 */
86 public static void addNew(){
87 System.out.println("-- Add a new student --");
88 System.out.println("What is their name?");
89 gradeBook[numStudents][0] = userInput.next();
90 System.out.println("What is their Math grade?");
91 gradeBook[numStudents][1] = userInput.next();
92 System.out.println("What is their English grade?");
93 gradeBook[numStudents][2] = userInput.next();
94 System.out.println("What is their Science grade?");
95 gradeBook[numStudents][3] = userInput.next();
96 System.out.println("What is their History grade?");
97 gradeBook[numStudents][4] = userInput.next();
98
99 System.out.println("Student added with these properties:");
100 printStudent(numStudents);
101
102 numStudents ++;
103 makeDecision();
104
105 }
106
107 /**
108 * Modify an existing student given their ID
109 */
110 public static void modifyStudent(){
111 System.out.println("-- Modify Student --");
112 System.out.println("Enter Student ID: ");
113 int studentID = userInput.nextInt();
114 if(studentID >= 0 && studentID < numStudents){
115 System.out.printf("\nModifying %s\n", gradeBook[studentID][0]);
116 System.out.println("Enter new name:");
117 gradeBook[studentID][0] = userInput.next();
118 System.out.println("Enter new Math grade?");
119 gradeBook[studentID][1] = userInput.next();
120 System.out.println("Enter new English grade?");
121 gradeBook[studentID][2] = userInput.next();
122 System.out.println("Enter new Science grade?");
123 gradeBook[studentID][3] = userInput.next();
124 System.out.println("Enter new History grade?");
125 gradeBook[studentID][4] = userInput.next();
126 System.out.println("Student has been updated with these details:");
127 printStudent(studentID);
128 }
129 else{
130 System.out.println("No student exists with this ID.");
131 }
132 makeDecision();
133
134 }
135
136 /**
137 * Print out a student's information
138 * @param studentID - The ID of the student being printed
139 */
140 public static void printStudent(int studentID){
141 System.out.printf("\nID: %d Name: %s Grades - Math: [%s] English: [%s] Science: [%s] History: [%s]", studentID, gradeBook[studentID][0], gradeBook[studentID][1], gradeBook[studentID][2], gradeBook[studentID][3], gradeBook[studentID][4]);
142 }
143
144 /**
145 * Calculate the student's GPA by adding all 4 grades together, and dividing by 4.
146 * You may use Double.valueOf(STRING) to get the double value of a String.
147 */
148 public static void calcGPA(){
149 System.out.println("Enter the student's ID:");
150 int studentID = userInput.nextInt();
151 //Check if this ID is between 0 and the number of students total
152 if(studentID >= 0 && studentID < numStudents) {
153 double GPA = 0;
154 GPA = Double.valueOf(gradeBook[studentID][1]) + Double.valueOf(gradeBook[studentID][2]) + Double.valueOf(gradeBook[studentID][3]) + Double.valueOf(gradeBook[studentID][4]);
155 GPA = GPA / 4;
156 System.out.printf("\n%s has a GPA of %f", gradeBook[studentID][0], GPA);
157 }
158 else{
159 System.out.println("No student exists with this ID.");
160 }
161 makeDecision();
162
163 }
164
165}
Spotted a mistake? Select the sentence in the guide and choose “Suggest a fix”.
Related guides
Simple Pong (Extras)
This guide is a continuation of the previous Simple Pong project. I'd encourage you to begin there if you haven't already. In this guide, you will learn how to…
Simple 2D Pong
The game will contain 4 classes. Main - Launches the program, starts the game and game timerPongGame - Extends JPanel, serves as the game's canvas, tracks…
GUI Blackjack
In this project, we will expand upon the earlier console blackjack project. You should begin there if you haven't already. This project relies on much of the…

Comments
Found an error? instead, it reaches me faster.No comments yet. Questions and corrections are welcome.