Multi Dimensional Array in Java

The Multi Dimensional Array in Java is nothing but an Array of Arrays (more than a single dimension). The previous article discussed the 2D Array, the simplest form of Multi Dimensional Array. In Java Programming, we can declare a 2D, n-dimensional, or Multi dimensional array by placing n number of brackets [ ], where n is the dimension number. For example,

int[2][3][4] StudentArr = 3D Array

int[2][2][3][4] StudentArr = 4D Array

This article will show how to declare and initialize Java Multi Dimensional Array. For Multi Dimensional Array better understanding, we are using Three Dimensional Array. Moreover, you can try four dimensional array using the same technique.

Declaration of Multi Dimensional Array in Java

It shows the declaration of the multi dimensional array in Java Programming

Data_Type[][][] Arr_Name;

Similarly, we can declare the other type of Multi Dimensional Array:

int [][][] anIntegerType;
byte[][][] aByteType;
short[][][] aShortType;
long[][][] aLongType;
float[][][] aFloatType;
double[][][] aDoubleType;
boolean[][][] aBooleanTypeArr; 
char[][][] aCharArr;
String[][][] aStringArr;

Creating Multi dimensional Array in Java

In order to create a multi dimensional array in Java, we have to use the New operator.

Data_Type[][][] Name = new int[Tables][Row_Size][Column_Size];

If you observe the above code snippet of this Java Multi Dimensional Array,

  • Tables: Total number of tables it can accept. A 2D Array is always a single table with rows and columns. In contrast, Multi Dimensional array is more than one table with rows and columns.
  • Row_Size: Number of Row elements. For example, Row_Size = 5, then the 3D array holds five rows.
  • Column_Size: Column elements it can store. Column_Size = 6, then the 3D array holds 6 Columns.

If you have already initialized a Java Multi Dimensional Array, then

double [][][] anEmployeeArr; // Declaration of Multidimensional array

// Crating an Java Multi dimensional Array
anEmployeeArr = new int[2][5][3];

For Example,

int [][][] Employees = new int[2][5][3];

  1. Here, we used int as the data type to declare an array. It means the above one will accept only double values, and if you try to add float or double values, it will throw an error.
  2. Employees is the name of the Java Multi Dimensional Array
  3. The number of tables = 2. So, this Multi dimensional array will hold a maximum of 2 levels of data (rows and columns).
  4. The Row size is 5, meaning employees only accept five integer values as rows.
    • If we try to store more than five values, it will throw an error.
    • We can store less than 5. For Example, If we store three integer values, the remaining two values will be initialized to a default value (Which is 0).
  5. And the Column size is three; it means Employees will only accept three integer values.
    • If we try to store more than three, it will throw an error.
    • We can store less than 3. For Example, If we store one integer value, the remaining two values will be initialized to the default value (Which is 0).
  6. Finally, the Employees can hold a maximum of 24 integer values (2 * 4 * 3 = 24).

Initialization of Multi Dimensional Array in Java

We can initialize the Java Multi dimensional Array in multiple ways

First Approach

Declaring and Creating a Java Multi-dimensional Array

int[][][] Student_Marks = new int[3][5][4];

Initializing elements in a more traditional way

Student_Marks[0][0][0] = 15; // Initializing elements at position [0][0][0]
Student_Marks[1][1][0] = 45; // Initializing elements at position [1][1][0]
Student_Marks[2][0][1] = 65; // Initializing elements at position [2][0][1]

Java Multi Dimensional Array Second Approach

int[][][] EmployeeArr = { { {10, 20, 30}, {50, 60, 70}, {80, 90, 100}, {110, 120, 130} },
                           { {15, 25, 35}, {22, 44, 66}, {33, 55, 77}, {78, 57, 76} }
                         };

We did not mention the data level, row size, and column size. However, the compiler is intelligent enough to calculate the size by checking the number of elements inside the row and column. Please refer to the Arrays and Two Dimensional articles.

Third Approach

The above two ways of initializing Java multi Dimensional arrays are good for storing a small number of elements in 3d or 4d. What if we want to store 100 rows or 50 column values in Java? Adding all of them using any approaches, as mentioned earlier, will be a nightmare. To resolve this, we can use the Nested For Loop in Java concept here:

int tables, rows, columns;		
for(tables = 0; tables < 2; tables++) {
	for(rows = 0; rows < 3; rows++) {
		for(columns = 0; columns < 4; columns++) {
			EmployeeArr[tables][rows][columns] = tables + rows + columns; 
		}
	}			
}

TIP: To store/load the elements in a Multi-Dimensional Array, you can use For loop, While Loop, and Do While Loop

Fourth Approach

int[][][] Employees = new int[2][5][3];
Employees[0][0][0] = 102;
Employees[0][0][1] = 202;
Employees[0][0][2] = 305;

Here, we declared a 3D array of size 2 levels * 5 rows * 3 columns, but we only assigned values for one row. In this situation, the remaining values will be default values (0 in this case).

Accessing Java Multi Dimensional Array Elements

In Java programming language, we can use the index position to access the multi dimensional array items. Using the index, we can access or alter/change every individual element present in the multi dimensional array.

The index value of Multi Dimensional Array starts at 0. It ends at n-1, where n is the size of tables, rows, or columns. For example, an int[][][] multiarr= new int[2][6][4] allows storing a maximum of two levels of data (rows and columns), 6-row elements, and 4 column elements. To access or alter 1st value use multiarr[0][0][0], to access or alter 2nd row 3rd column at 1st level, use multiarr[0][1][2]. And to get the 6th-row 4th column in the 2nd level, multiarr[1][5][3].

public class Sample {
	public static void main(String[] args) {
		int[][][] Student = { { {10, 20, 30}, {50, 60, 70}, {80, 90, 100}, {110, 120, 130} },
                                   { {15, 25, 35}, {22, 44, 66}, {33, 55, 77}, {78, 57, 76} }
                                  };
		System.out.println("Element at Student[0][0][0] = " + Student[0][0][0]);
		System.out.println("Element at Student[0][0][1] = " + Student[0][0][1]);
		System.out.println("Element at Student[0][0][2] = " + Student[0][0][2]);
		System.out.println("Element at Student[0][1][0] = " + Student[0][1][0]);
		System.out.println("Element at Student[0][1][1] = " + Student[0][1][1]);
		System.out.println("Element at Student[0][1][2] = " + Student[0][1][2]);
		System.out.println("Element at Student[0][2][0] = " + Student[0][2][0]);
		System.out.println("Element at Student[0][2][1] = " + Student[0][2][1]);
		System.out.println("Element at Student[0][2][2] = " + Student[0][2][2]);
		System.out.println("Element at Student[0][3][0] = " + Student[0][3][0]);
		System.out.println("Element at Student[0][3][1] = " + Student[0][3][1]);
		System.out.println("Element at Student[0][3][2] = " + Student[0][3][2]);
		
		//Accessing Second Table Rows & Columns
		System.out.println("=============");
		System.out.println("Element at Student[1][0][0] = " + Student[1][0][0]);
		System.out.println("Element at Student[1][0][1] = " + Student[1][0][1]);
		System.out.println("Element at Student[1][0][2] = " + Student[1][0][2]);
		System.out.println("Element at Student[1][1][0] = " + Student[1][1][0]);
		System.out.println("Element at Student[1][1][1] = " + Student[1][1][1]);
		System.out.println("Element at Student[1][1][2] = " + Student[1][1][2]);
		System.out.println("Element at Student[1][2][0] = " + Student[1][2][0]);
		System.out.println("Element at Student[1][2][1] = " + Student[1][2][1]);
		System.out.println("Element at Student[1][2][2] = " + Student[1][2][2]);
		System.out.println("Element at Student[1][3][0] = " + Student[1][3][0]);
		System.out.println("Element at Student[1][3][1] = " + Student[1][3][1]);
		System.out.println("Element at Student[1][3][2] = " + Student[1][3][2]);
	}
}

The Multi dimensional array output

Element at Student[0][0][0] = 10
Element at Student[0][0][1] = 20
Element at Student[0][0][2] = 30
Element at Student[0][1][0] = 50
Element at Student[0][1][1] = 60
Element at Student[0][1][2] = 70
Element at Student[0][2][0] = 80
Element at Student[0][2][1] = 90
Element at Student[0][2][2] = 100
Element at Student[0][3][0] = 110
Element at Student[0][3][1] = 120
Element at Student[0][3][2] = 130
=============
Element at Student[1][0][0] = 15
Element at Student[1][0][1] = 25
Element at Student[1][0][2] = 35
Element at Student[1][1][0] = 22
Element at Student[1][1][1] = 44
Element at Student[1][1][2] = 66
Element at Student[1][2][0] = 33
Element at Student[1][2][1] = 55
Element at Student[1][2][2] = 77
Element at Student[1][3][0] = 78
Element at Student[1][3][1] = 57
Element at Student[1][3][2] = 76

In order to work with a large number of rows and columns, we have to use For loop. Let us access the above array Student[2][4][3] using For loop.

int tables, rows, columns;

for (tables = 0; tables < 2; tables++) {
     for (rows = 0; rows < 4; rows++) {
          for (columns = 0; columns < 3; columns++) {
	       System.out.format("%d", Student[tables][rows][columns]);
          }
     }
}

Multi Dimensional Array in Java example

In this program, We will declare 2 Multi dimensional arrays and initialize them with some values. Then we declared one more multi dimensional array to save the sum.

// Example 

public class AccessTwoDimentionalArray {
	public static void main(String[] args) {
		int[][][] a = { { {2, 4, 6, 8}, {12, 14, 16, 18}, {22, 24, 26, 28} }, 
                        { {32, 34, 36, 38}, {52, 54, 56, 58}, {72, 74, 76, 78} } };
		int[][][] b = { { {10, 20, 30, 40}, {50, 60, 70, 80}, {100, 110, 120, 140} }, 
                        { {150, 160, 170, 180}, {190, 200, 220, 240}, {250, 270, 290, 300} }
                      };
		int[][][] Sum = new int[2][3][4];
		int tables, rows, columns;		
		for(tables = 0; tables < a.length; tables++) {
			for(rows = 0; rows < a[0].length; rows++) {
				for(columns = 0; columns <= a[1].length; columns++) {
					Sum[tables][rows][columns] = a[tables][rows][columns] + b[tables][rows][columns]; 
				}
			}			
		}
		System.out.println("Sum Of those Two Arrays are: ");
		for(tables = 0; tables < a.length; tables++) {
			for(rows = 0; rows < a[0].length; rows++) {
				for(columns = 0; columns <= a[1].length; columns++) {
					System.out.format("%d \t", Sum[tables][rows][columns]);
				}
				System.out.println("");
			}
			System.out.println("");
		}
	}
}
Multi Dimensional Array in Java 2

In this Java Multi Dimensional Array example, First, We declared two 3 Dimensional Arrays a, b of size [2],[3], and initialized them with some random values. We also declared an empty array of sizes [2],[3]

Below For loop will help to iterate every cell present in both a and b. Condition inside the for loops (rows < a[0].length) will ensure the compiler not to exceed the array row limit, and (columns < a[1].length) will ensure the compiler not to exceed the array column limit.

TIP: a.length is to find the level of data (first dimension), a[0].length is used to find the length of the rows (second dimension), and a[1].length is used to find the length of the columns (third dimension).

for(tables = 0; tables < a.length; tables++) {
	for(rows = 0; rows < a[0].length; rows++) {
		for(columns = 0; columns <= a[1].length; columns++) {
			Sum[tables][rows][columns] = a[tables][rows][columns] + b[tables][rows][columns]; 
		}
	}			
}

Analysis

Let us see the Java Multi Dimensional Array program iteration wise

Tables First Iteration

The value of tables = 0, and the condition (tables < 2) is True. So, it will enter into the second for loop (Row Iteration).

Row First Iteration

The value of the row = 0, and the condition (rows < 2) is True. So, it enters into the second for loop.

Column First Iteration

The value of the column= 0, and the condition (columns < 3) is True. So, it will start executing the statements inside the loop until the condition fails.

  • Sum[tables][rows][columns] = a[tables][rows][columns] + b[tables][rows][columns];
  • Sum[0][0][0] = a[0][0][0] + b[0][0][0] = 2 + 10 = 12;

The value of the column will increment by 1.

Second Iteration: The value of the column= 1, and the condition (columns <= 3) is True. Since we didn’t exit from the inner loop (Columns loop), the row value is still 0

  • Sum[0][0][1]= a[0][0][1] + b[0][0][1] = 4 + 20;
  • Sum[0][0][1]= 24;

The column will increment by 1.

3rd Iteration: The value of the columns is 2, and the condition (columns <= 3) is True. Since we didn’t exit from the inner loop (Columns loop), the row value will be 0

  • Sum[0][0][2] = a[0][0][2] + b[0][0][2] = 6 + 30;
  • Sum[0][0][2] = 36;

column incremented by 1.

fourth Iteration: The value of the column= 3, and the condition (columns <= 3) is True. Since we didn’t exit from the inner loop (Columns loop), the row value will be 0

Sum[0][0][3] = a[0][0][2] + b[0][0][2] = 8 + 40;

Sum[0][0][3] = 48;

From the fourth iteration, the value of the columns became 4, and the condition (columns <= 3) will fail. So it will exit from the loop. Now the value of rows will be incremented by 1 and starts the second row iteration.

Java Multi Dimensional Array – Row Second Iteration

The value of the row will be 1, and the condition (rows < 2) is True. So, it will enter into the second for loop

Column First Iteration

The value of the column= 0, and the condition (columns <= 3) is True. So, it will start executing the statements inside the loop until the condition fails.

  • Sum[0][1][0] = a[0][1][0] + b[0][1][0];
  • Sum[0][1][0] = 12 + 50 = 62;

column incremented by 1.

Second Iteration: The value of the columns= 1, and the condition (columns <= 3) is True.

  • Sum[0][1][1]= a[0][1][1] + b[0][1][1] = 14 + 60;
  • Sum[0][1][1]= 74;

The value of the column will be incremented by 1

3rd Iteration: The value of the columns= 2, and the condition (columns <= 3) is True.

  • Sum[0][1][2] = a[0][1][2] + b[0][1][2] = 16 + 70;
  • Sum[0][1][2] = 86;

fourth Iteration: The value of the columns= 3, and the condition (columns <= 3) is True.

  • Sum[0][1][3] = a[0][1][2] + b[0][1][2] = 18 + 80;
  • Sum[0][1][3] = 98;

After the increment, the value of columns will be four, and the condition (columns <= 3) will fail. So it will exit from the Column For loop. Next, the value of rows will be incremented by 1. It means rows = 2. Condition (rows < 2) will fail. So, it will exit from the Row loop.

Now, the value of tables will be incremented by 1. It means tables = 1, and the Condition (tables < 2) is TRUE. So, it will start executing Tables Second Iteration. Repeat the above process one more time to get the remaining results.

Next for loops in the Java Multi Dimensional Array will traverse, as explained above. However, instead of summing, it will display the values individually with tab separation using the system.out.format statement inside them.