Two Dimensional Array in Java

The Two Dimensional Array in Java programming language is nothing but an Array of Arrays. In Java Two Dimensional Array, data stored in row and columns, and we can access the record using both the row index and column index (like an Excel File).

If the data is linear, we can use the One Dimensional Array. However, to work with multi-level data, we have to use the Multi-Dimensional Array. Two Dimensional Array in Java is the simplest form of Multi-Dimensional Array.

Two Dimensional Array Declaration in Java

The following code snippet shows the two dimensional array declaration in Java Programming Language:

Data_Type[][] Array_Name;
  • Data_type: It decides the type of elements it will accept. For example, If we want to store integer values, then the Data Type will be declared as int. If we want to store Float values, then the Data Type will be float.
  • Array_Name: This is the name to give it to this Java two dimensional array. For example, Car, students, age, marks, department, employees, etc.

Similarly, one can declare the remaining type of two-dimensional arrays:

int [][] anIntegerArray; // declaring an two dimensional array of Integers
byte[][] anByteArray; // declaring an two dimensional array of Bytes
short[][] anShortArray; // declaring an two dimensional array of Shorts
long[][] anLongArray; // declaring an two dimensional array of Longs
float[][] anFloatArray; // declaring an two dimensional array of Floats
double[][] anDoubleArray; // declaring an two dimensional array of Doubles
boolean[][] anBooleanArray; // declaring an two dimensional array of Booleans
char[][] anCharArray; // declaring an two dimensional array of Chars
String[][] anStringArray; // declaring an two dimensional array of Strings

Create Two dimensional Array in Java

In order to create a two dimensional array in Java, we have to use the New operator as we shown below:

Data_Type[][] Array_Name = new int[Row_Size][Column_Size];

If we observe the above two dimensional array code snippet,

  • Row_Size: Number of Row elements an array can store. For example, Row_Size = 5, then the array will have five rows.
  • Column_Size: Number of Column elements an array can store. For example, Column_Size = 6, then the array will have 6 Columns.

If you already initialized a two dimensional array in Java, then

double [][] anStudentArray; // Declaration of Two dimensional array in java 

// Crating an Java two dimensional Array
anStudentArray = new int[5][3];

For Example,

double [][] Employees = new double[5][3];

  1. Here, we used double as the data type to declare a two dimensional array in Java. It means, the above array will accept only double values, and if you try to add float values, then it will throw an error.
  2. Employees is the name of the Two Dimensional Array
  3. The Row size of an Array is 5, and it means Employees array will only accept 5 double values as rows.
    • If we try to store more than 5 values, then it will throw an error.
    • We can store less than 5. For Example, If we store 2 integer values, then the remaining 2 values will be initialized to the default value (Which is 0).
  4. The Column size of an Array is 3. It means Employees array will only accept 3 integer values as columns.
    • If we try to store more than 3, then it will throw an error.
    • We can store less than 3. For Example, If we store 1 integer value, then the remaining 2 values will be initialized to the default value (Which is 0).

Initialization of Two Dimensional Array in Java

We can initialize the Java Two Dimensional Array in multiple ways. Please refer to Arrays and Multi-Dimensional Array in Java Programming.

Two Dimensional Array First Approach

Declaring and Creating a Two Dimensional Array in Java

int[][] Student_Marks = new int[2][3];

Initialize Array elements more traditionally.

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

Java two dimensional array Second Approach

The second approach of declaring and Creating a Two Dimensional Array

int[][] Student_Marks = new int[2][];

Here, We did not mention the column size. However, the Jcompiler is intelligent enough to calculate the size by checking the number of elements inside the column.

Java two dimensional array Third Approach

int[][] Employees = { {10, 20, 30}, {15, 25, 35}, {22, 44, 66}, {33, 55, 77} };

Here, We did not mention the 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.

Fourth Approach

The above 3 ways are good to store a small number of elements into the two dimensional array in Java, What if we want to store 100 rows or 50 column values. It will be a nightmare to add all of them using any of the approaches mentioned above. To resolve this, we can use the Nested For Loop concept here:

int rows, columns;
int[][] Employees = new int[100][50];

for (rows = 0; rows < 100 ; rows++) {
	for (columns = 0; columns < 50; columns++) {
		Employees[rows][columns] = rows + columns;
	}
}

TIP: In order to store the elements in a Java Two Dimensional Array, We can use For loop, While Loop and Do While Loop

Fifth Approach for Two Dimensional array in Java

int[][] anIntegerArray = new int[5][3];
anIntegerArray[0][0] = 10;
anIntegerArray[0][1] = 20;
anIntegerArray[0][2] = 30;

Here we declared a Java two dimensional array of size 5 rows * 3 columns, but we only assigned values for one row. In this situation, the remaining values assigned to default values (0 in this case).

Access Java Two Dimensional Array Elements

In Java programming, We can use the index position to access the two dimensional array elements. Using the index, we can access or alter/change every individual element present in a two dimensional array.

An index value of a Java two dimensional array starts at 0 and ends at n-1 where n is the size of a row or column. For example, if an int[][] Array_name = new int[6][4] will stores 6 row elements and 4 column elements.

To access or alter 1st value use Array_name[0][0], to access or alter 2nd row 3rd column value then use Array_name[1][2] and to access the 6th row 4th column then use Array_name[5][3]. Let’s see the example of the two dimensional array for better understanding:

package ArrayDefinitions;

public class AccessTwoDimentionalArray {
	public static void main(String[] args) {
		int[][] StudentArray = { {12, 22, 33},{45, 65, 95},{442, 444, 446},{785, 786, 787}};

		System.out.println("Element at StudentArray[0][0] = " + StudentArray[0][0]);
		System.out.println("Element at StudentArray[0][1] = " + StudentArray[0][1]);
		System.out.println("Element at StudentArray[0][2] = " + StudentArray[0][2]);
		System.out.println("Element at StudentArray[1][0] = " + StudentArray[1][0]);
		System.out.println("Element at StudentArray[1][1] = " + StudentArray[1][1]);
		System.out.println("Element at StudentArray[1][2] = " + StudentArray[1][2]);
		System.out.println("Element at StudentArray[2][0] = " + StudentArray[2][0]);
		System.out.println("Element at StudentArray[2][1] = " + StudentArray[2][1]);
		System.out.println("Element at StudentArray[2][2] = " + StudentArray[2][2]);
	}
}

Java 2D array Output

Element at StudentArray[0][0] = 12
Element at StudentArray[0][1] = 22
Element at StudentArray[0][2] = 33
Element at StudentArray[1][0] = 45
Element at StudentArray[1][1] = 65
Element at StudentArray[1][2] = 95
Element at StudentArray[2][0] = 442
Element at StudentArray[2][1] = 444
Element at StudentArray[2][2] = 446

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[4][3] using For loop.

int rows, columns;

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

Java Two Dimensional Array example

In this Java two dimensional array program, we will declare 2 Two dimensional arrays.

Next, we initialize them with some values. Then we will declare one more Two dimensional array to store the sum those two arrays.

// Two Dimensional Array in Java Example 
package ArrayDefinitions;

public class TwoDimentionalArray {
	public static void main(String[] args) {
		int[][] a = { {15, 25, 35}, {45, 55, 65} };
		int[][] b = {{12, 22, 32}, {55, 25, 85} };
		int[][] Sum = new int[2][3];
		int rows, columns;
		
		for(rows = 0; rows < a.length; rows++) {
			for(columns = 0; columns < a[0].length; columns++) {
				Sum[rows][columns] = a[rows][columns] + b[rows][columns];  
			}			
		}
		System.out.println("Sum Of those Two Arrays are: ");
		for(rows = 0; rows < a.length; rows++) {
			for(columns = 0; columns < a[0].length; columns++) {
				System.out.format("%d \t", Sum[rows][columns]);
			}
			System.out.println("");
		}
	}
}
Two Dimensional Array in Java 2

In this two dimensional array program, First, We declared 2 two 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 = { {15, 25, 35}, {45, 55, 65} };
int[][] b = {{12, 22, 32}, {55, 25, 85} };
int[][] Sum = new int[2][3];

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

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

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

Let us see the Java two dimensional array program execution in iteration wise

Row First Iteration

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

Column First Iteration

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

  • Sum[rows][columns] = a[rows][columns] + b[rows][columns];
  • Sum[0][0] = a[0][0] + b[0][0];
  • Sum[0][0] = 15 + 12;
  • Sum[0][0] = 27;

The value of the column incremented by 1

Column Second Iteration

The value of the column is 1, and the condition (columns < 3) is True. Since we did not exit from the inner loop (Columns loop), the row value is still 0.

  • Sum[0][1]= a[0][1] + b[0][1];
  • Sum[0][1]= 25 + 22 = 47;

The value of the column incremented by 1

Column 3rd Iteration

The value of columns is 2, and the condition (columns < 3) is True. Since we did not exit from the inner loop, the row value will be 0.

  • Sum[0][2] = a[0][2] + b[0][2];
  • Sum[0][2] = 35 + 32 = 67;

After the increment, the value of columns will be 3, and the condition (columns < 3) will fail. So it will exit from the loop.

Now the value of rows will be incremented by one and starts the second-row iteration.

Second Row Second Iteration

The value of the 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[rows][columns] = a[rows][columns] + b[rows][columns];
  • Sum[1][0] = a[1][0] + b[1][0];
  • Sum[1][0] = 45 + 55;
  • Sum[1][0] = 100;

The value of the column incremented by 1

Column Second Iteration

The value of the column is 1, and the condition (columns < 3) is True. Since we did not exit from the Columns loop, the row value will be 1

  • Sum[1][1]= a[1][1] + b[1][1];
  • Sum[1][1]= 55 + 25;
  • Sum[1][1]= 80;

The value of the column incremented by 1

Column 3rd Iteration

The value of columns is 2, and the condition (columns < 3) is True. Since we did not exit from the inner loop (Columns loop), the row value will be 1.

  • Sum[1][2] = a[1][2] + b[1][2] = 65 + 85;
  • Sum[1][2] = 150;

After the increment, the value of columns will be three, and the condition (columns < 3) will fail. So it will exit from the loop. Now the value of rows will increment by 1. It means rows = 2. Condition (rows < 2) will fail. So, it will exit from the loop.

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

for(rows = 0; rows < a.length; rows++) {
	for(columns = 0; columns < a[0].length; columns++) {
		System.out.format("%d \t", Sum[rows][columns]);
	}
	System.out.println("");
}

The final output of the Java two dimensional array (Sum array) is:

Sum[2][3] = { {27, 47, 67}, {100, 80, 150} };