Multi Dimensional Array in Java

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

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

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

In this article, we will show how to declare, initialize Multi Dimensional Array in Java. For Java 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[][][] Array_Name;

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

int [][][] anIntegerArray;
byte[][][] anByteArray;
short[][][] anShortArray;
long[][][] anLongArray;
float[][][] anFloatArray;
double[][][] anDoubleArray;
boolean[][][] anBooleanArray; 
char[][][] anCharArray;
String[][][] anStringArray;

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[][][] Array_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 an array can accept. 2D Array is always a single table with rows and columns. In contrast, Multi Dimensional array in Java 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 already initialized a Java Multi Dimensional Array then

double [][][] anStudentArray; // Declaration of Multidimensional array in java 

// Crating an Java Multi dimensional Array
anStudentArray = 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 array 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 of an Array is 5, and it means Employees array will only accept five integer values as rows.
    • If we try to store more than five values, then it will throw an error.
    • We can store less than 5. For Example, If we store three integer values, then the remaining two values will be initialized to a default value (Which is 0).
  5. And the Column size of an Array is three; it means Employees array will only accept three integer values as columns.
    • If we try to store more than three, then it will throw an error.
    • We can store less than 3. For Example, If we store one integer values, then the remaining two values will be initialized to the default value (Which is 0).
  6. Finally, the Employees array 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 Array elements in a more traditional way

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

Second Approach

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

Here, 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 Arrays and Two Dimensional Array article.

Third Approach

The above two ways are good to store a small number of elements into the array. What if we want to store 100 rows or 50 column values in Java. It will be a nightmare to add all of them using any of the approaches, as mentioned earlier. 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++) {
			StudentArray[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 Multi Dimensional Array Elements

In Java, 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 in Java 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].

package ArrayDefinitions;

public class AccessMultiDimentionalArray {
	public static void main(String[] args) {
		int[][][] StudentArray = { { {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 StudentArray[0][0][0] = " + StudentArray[0][0][0]);
		System.out.println("Element at StudentArray[0][0][1] = " + StudentArray[0][0][1]);
		System.out.println("Element at StudentArray[0][0][2] = " + StudentArray[0][0][2]);
		System.out.println("Element at StudentArray[0][1][0] = " + StudentArray[0][1][0]);
		System.out.println("Element at StudentArray[0][1][1] = " + StudentArray[0][1][1]);
		System.out.println("Element at StudentArray[0][1][2] = " + StudentArray[0][1][2]);
		System.out.println("Element at StudentArray[0][2][0] = " + StudentArray[0][2][0]);
		System.out.println("Element at StudentArray[0][2][1] = " + StudentArray[0][2][1]);
		System.out.println("Element at StudentArray[0][2][2] = " + StudentArray[0][2][2]);
		System.out.println("Element at StudentArray[0][3][0] = " + StudentArray[0][3][0]);
		System.out.println("Element at StudentArray[0][3][1] = " + StudentArray[0][3][1]);
		System.out.println("Element at StudentArray[0][3][2] = " + StudentArray[0][3][2]);
		
		//Accessing Second Table Rows & Columns
		System.out.println("=============");
		System.out.println("Element at StudentArray[1][0][0] = " + StudentArray[1][0][0]);
		System.out.println("Element at StudentArray[1][0][1] = " + StudentArray[1][0][1]);
		System.out.println("Element at StudentArray[1][0][2] = " + StudentArray[1][0][2]);
		System.out.println("Element at StudentArray[1][1][0] = " + StudentArray[1][1][0]);
		System.out.println("Element at StudentArray[1][1][1] = " + StudentArray[1][1][1]);
		System.out.println("Element at StudentArray[1][1][2] = " + StudentArray[1][1][2]);
		System.out.println("Element at StudentArray[1][2][0] = " + StudentArray[1][2][0]);
		System.out.println("Element at StudentArray[1][2][1] = " + StudentArray[1][2][1]);
		System.out.println("Element at StudentArray[1][2][2] = " + StudentArray[1][2][2]);
		System.out.println("Element at StudentArray[1][3][0] = " + StudentArray[1][3][0]);
		System.out.println("Element at StudentArray[1][3][1] = " + StudentArray[1][3][1]);
		System.out.println("Element at StudentArray[1][3][2] = " + StudentArray[1][3][2]);
	}
}

Java multi dimensional array output

Element at StudentArray[0][0][0] = 10
Element at StudentArray[0][0][1] = 20
Element at StudentArray[0][0][2] = 30
Element at StudentArray[0][1][0] = 50
Element at StudentArray[0][1][1] = 60
Element at StudentArray[0][1][2] = 70
Element at StudentArray[0][2][0] = 80
Element at StudentArray[0][2][1] = 90
Element at StudentArray[0][2][2] = 100
Element at StudentArray[0][3][0] = 110
Element at StudentArray[0][3][1] = 120
Element at StudentArray[0][3][2] = 130
=============
Element at StudentArray[1][0][0] = 15
Element at StudentArray[1][0][1] = 25
Element at StudentArray[1][0][2] = 35
Element at StudentArray[1][1][0] = 22
Element at StudentArray[1][1][1] = 44
Element at StudentArray[1][1][2] = 66
Element at StudentArray[1][2][0] = 33
Element at StudentArray[1][2][1] = 55
Element at StudentArray[1][2][2] = 77
Element at StudentArray[1][3][0] = 78
Element at StudentArray[1][3][1] = 57
Element at StudentArray[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 StudentArray[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", StudentArray[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.

// Multi Dimensional Array in Java Example 
package ArrayDefinitions;

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 with some random values. We also declared an empty array of size[2],[3]

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];

Below For loop will help to iterate every cell present in both a and b array. 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]; 
		}
	}			
}

Let us see the Java Multi Dimensional Array program in the iteration wise

Tables First Iteration

The value of tables = 0, and the condition (tables < 2) is True. So, it will enter into 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 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 column will increment by 1

Column Second Iteration

The value of the column is 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;

column incremented by 1

Column 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

Column fourth Iteration

The value of the columns is 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 row will be 1 and the condition (rows < 2) is True. So, it will enter into second for loop

Column First Iteration

The value of the column is 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

Column Second Iteration

The value of the column is 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 column will be incremented by 1

Column 3rd Iteration

The value of the columns is 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;

Column fouth Iteration

The value of the columns is 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 for one more time to get the remaining results.

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

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("");
}