# Multidimensional Array in Java | 2D Array, Example

Multidimensional array in Java represents 2D, 3D, . . . . arrays which is a combination of several types of arrays.

For example, a two-dimensional array is a combination of two or more one-dimensional (1D) arrays.

Similarly, a three-dimensional array is a combination of two or more two-dimensional (2D) arrays.

Let us understand the concepts of two dimensional arrays in java first in detail. In the next tutorial, we will concentrate on three-dimensional arrays.

## Two Dimensional Array (2D array) in Java

A two dimensional array in java represents many rows and columns of data. Data in matrix or table form can be represented by using two dimensional array.

A matrix is a group of elements arranged into many rows and columns. We can use two dimensional array to store elements of a matrix or table.

For example, marks obtained by a group of three students in five different subjects can be represented in table form like this:

Students Physics Chemistry Maths Computer English
Deep
80
97
80
99
82
Amit
99
98
100
81
97
Larry
87
99
93
95
97

We can store marks of three students in the above table using two dimensional array as:

```int marks[ ] [ ] = {
{80, 97, 80, 99, 82},
{99, 98, 100, 81, 97},
{87, 99, 93, 95, 97}
};
```

The above marks obtained by three students in five subjects represent two dimensional array (2D array) since it is a combination of 3 rows (no. of students) and 5 columns (no. of subjects).

We can consider each row itself as a one dimensional array. This two-dimensional array (2D array) contains three one-dimensional arrays. So, it is called multidimensional arrays in java.

## How to Declare and Initialize Two Dimensional Array in Java

There are mainly two ways to create a two-dimensional array in java that are as follows:

1. The syntax to create a two dimensional array and directly store elements at the time of its declaration, as follows:

```int marks[ ] [ ] = {{50, 60, 78, 87, 95},
{98, 87, 75, 76, 99},
{98, 99, 97, 95, 100}
};
```

Here, int represents the types of elements stored in an array. We have stored integer type elements in this array. “marks” represents array name.

Two pairs of square braces ([ ] [ ]) after array name represents a two dimensional array. Elements of each row must be written inside the curly braces { and }.

The rows and elements in each row must be separated by commas. Since there are three rows and five columns in each row, JVM creates 3 * 5 = 15 memory blocks as there are 15 elements being stored into the array. These blocks of memory can be individually referred to as:

```marks, marks, marks, marks, marks
marks, marks, marks, marks, marks
marks, marks, marks, marks, marks
```

As you can observe that rows are starting from 0 to 2 and columns are starting from 0 to 4. So, in general form, any element can be referred to as marks[i][j] where i and j are two indexes that represent row position and column position respectively.

Look at the figure below where the arrangement of elements in a 2D array. Key point:

1. In a two-dimensional array, an element is accessed through a row and column index.

2. The second way for creating a two dimensional array is that first declare an array and then allocate memory for it using the new operator.

The syntax to declare a two dimensional array 3-by-5 of type int is as follows:

```int[ ][ ] marks; // declaring a marks array.
marks = new int; // allocating memory for storing 15 elements.
```

The predecessor two statements can be written by combining them into a single statement, as:

```int[ ][ ] marks = new int;
```

Here, JVM allocates memory for storing 15 integer values into the array. But so far, we have not stored 15 values into an array.

We can store elements into a two-dimensional array by accepting them from the keyboard and from within the program also. Look at the several types of examples for 2D arrays in java in the figure below: Let us take some more examples for two dimensional arrays in Java:

```1. float[ ] [ ] x = {{1.1f, 1.2f, 1.3f },
{2.1f, 2.2f, 2.3f},
{3.1f, 3.2f, 3.3f}
};
2. double[ ] [ ] y = {{10.2, 15.5}, {1.5, 2.5}};
3. byte[ ][ ] b = new byte;
4. String[ ][ ] str = new String[ 3];
5. int[ ][ ] values = new int;
```

## Ways for declaring 2D Array in Java

While declaring two dimensional array, we can write the two pairs of square braces before or after the array name, as:

```String str[ ][ ] = new String; // Allowed but not preferred.
Or,
String[ ][ ] str = new String; // Allowed and most preferred way.
```

## Obtaining Lengths of Two Dimensional Array

A two dimensional array is one dimensional array in which each element is another one dimensional array. The length of an array marks is the number of elements in the array, which can be obtained using marks.lenght.

marks, marks, marks, . . . . marks[marks.length – 1] are arrays. Their lengths can be obtained using marks.length, marks.length, . . . . .marks[marks.length – 1].

For example, suppose marks = new int, marks, marks1], and marks are one-dimensional arrays and each contains four elements. marks.length is 3, and marks.length, marks.length, and marks.length are 4.

## Jagged Array in Java

Since each row in a two dimensional array is itself an array, therefore, rows can have different lengths or sizes. A two-dimensional array with different rows is called jagged array in java.

Jagged array is also called ragged array in java. An example of creating a jagged array is as follows:

```int[ ][ ]  arr = {
{11, 12, 13, 14, 15},
{7, 8, 9, 10},
{4, 5, 6},
{2, 3},
{1}
};
```

As you can see in the preceding code, arr.length is 5, arr.length is 4, arr.length is 3, arr.length is 2, and arr.length is 1.

We can create a jagged array using the following syntax.

```int[ ][ ] arr = new int[ ];
arr = new int;
arr = new int;
arr = new int;
arr = new int;
arr = new int;
```

Now we can initialize values in jagged array like this:

```arr = 90;
arr = 75;
```

The first index must be specified in the syntax new int[ ] for creating an array. The syntax new int[ ][ ] would be wrong.

## Java Two Dimensional Array Example Programs

1. Let us create a program where we will create a 2D array and display its elements in the matrix form. To display elements of a two-dimensional array, we will use nested for loop. The outer for loop represents rows and the inner one represents columns of each loop.

Program source code 1:

```package arraysProgram;
public class TwoDArrayExample {
public static void main(String[] args)
{
// Create a 2D array of int type.
int[ ][ ] x = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Read and display array elements in a matrix form.
System.out.println("Displaying elements of 2D array in a matrix form:");
// Applying nested for loop.
for(int i = 0; i < 3; i++) // Outer for loop for Rows
{
for(int j = 0; j < 3; j++) // Columns in each row.
{
System.out.print(x[i][j]+ "\t");
}
System.out.println(); // next line.
}
}
}
```
```Output:
Displaying elements of 2D array in a matrix form:
1	2	3
4	5	6
7	8	9
```

In two dimensional array, we have used two for loops to display elements. Similarly, elements of three dimensional array can be displayed by using three for loops.

2. Let’s create a program where we will calculate the sum of all elements by columns and the sum of all elements in the 2D array.

Program source code 2:

```package arraysProgram;
public class TwoDArrayExample {
public static void main(String[] args)
{
// Create a 2D array of int type.
int[ ][ ] x = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Calculating the sum of elements in rows and columns.
int sum = 0;
for(int i = 0; i < x.length; i++) // Outer for loop for Rows
{
for(int j = 0; j < x[i].length; j++) // Columns in each row.
{
sum += x[i][j];
}
}
System.out.print("Sum: " +sum);
System.out.println();

// Calculating the sum of all elements in each columns.
for (int j = 0; j < x.length; j++)
{
int total = 0;
for (int i = 0; i < x.length; i++)
total += x[i][j];
System.out.println("Sum of elements in column " + j + " is " + total);
}
}
}
```
```Output:
Sum: 45
Sum of elements in column 0 is 12
Sum of elements in column 1 is 15
Sum of elements in column 2 is 18
```

3. Let’s take an example program where we will calculate the total marks obtained in three subjects by three students and display their percentages.

Program source code 3:

```package arraysProgram;
public class StudentMarks {
public static void main(String[] args)
{
String[ ] str = {"Deep", "Amit","Larry"}; // One dimensional array.
int[ ][ ] marks = new int; // Two dimensional array.

// Allocating memory for marks obtained in three subjects by student Deep.
marks = 80;
marks = 97;
marks = 80;
// Allocating memory for marks obtained in three subjects by student Amit.
marks = 99;
marks = 98;
marks = 100;
// Allocating memory for marks obtained in three subjects by student Larry.
marks = 87;
marks = 99;
marks = 93;

for(int i = 0; i < marks.length; i++)
{
int total = 0;
for(int j = 0; j < marks.length; j++)
{
total = total + marks[i][j];
}
for(int k = 0; k < str.length; k++)
{
System.out.println("Total marks obtained by student " +str[k]+": " +total);
double perc = (double)total/3;
System.out.println("Percentage: " +perc);
}
}}
}
```
```Output:
Total marks obtained by student Deep: 279
Percentage: 93.0
Total marks obtained by student Amit: 279
Percentage: 93.0
Total marks obtained by student Larry: 279
Percentage: 93.0
```

4. Since multidimensional array in java is actually arrays of arrays, therefore, the length of each array is under our control. We do not need to allocate the same number of elements for each dimension.

Let’s take an example program where we will create a two-dimensional array in which sizes of the second dimension are unequal.

That is, we will allocate manually different sizes for the second dimensions. This kind of array is called ragged array in java.

Program source code 4:

```package arraysProgram;
public class RaggedArray {
public static void main(String[] args)
{
int[ ][ ] x = new int[ ];
x = new int;
x = new int;
x = new int;
x = new int;

int i, j, k = 0;
for(i = 0; i < 4; i++)
{
for(j = 0; j < i + 1; j++)
{
x[i][j] = k;
k++;
}
}
for(i=0; i<4; i++)
{
for(j=0; j<i+1; j++)
System.out.print(x[i][j] + " ");
System.out.println();
}
}
}
```
```Output:
0
1 2
3 4 5
6 7 8 9
```

## How to find transpose of Matrix in Java Multidimensional Array?

5. Let’s write a program to find the transpose of a given matrix. The transpose of a matrix is a matrix that is obtained by converting rows as columns and columns as rows.

Suppose we have a matrix with 3 rows and 4 columns. Its transpose matrix will have 4 rows and 3 columns. In this program, we will take an original matrix of 3 rows and 3 columns.

Program source code 5:

```package arraysProgram;
public class Transpose {
public static void main(String[] args)
{
// Create an two dimensional array with size .
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

System.out.println("Original matrix: ");
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
System.out.println("Transpose matrix: ");
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.print(arr[j][i]+ " ");
}
System.out.println();
}
}
}
```
```Output:
Original matrix:
1 2 3
4 5 6
7 8 9
Transpose matrix:
1 4 7
2 5 8
3 6 9```

6. Let us create a program where we will find out the transpose of a given matrix. In this program, we will accept the integer values as input from the keyboard using Java Scanner class.

You can also use InputStreamReader class to accept input from the keyboard and BufferedReader class. Look at the source code below.

Program source code 6:

```package arraysProgram;
import java.util.Scanner;
public class Transpose {
public static void main(String[] args)
{
// Create an object of Scanner class to accept data from the keyboard.
Scanner sc = new Scanner(System.in);
// Get the rows and columns of a matrix.
System.out.println("Enter rows and columns?");
int r = sc.nextInt();
int c = sc.nextInt();

// Create an array with size [r][c].
int[ ][ ] arr = new int[r][c];
// Get elements of matrix from the keyboard.
System.out.println("Enter integer elements of matrix ");
for(int i = 0; i < r; i++) // Outer for loop for rows.
{
for(int j = 0; j < c; j++) // Inner for loop for columns.
{
arr[i][j] = sc.nextInt();
}
}
System.out.println("Transpose matrix: ");
for(int i = 0; i < c; i++)
{
for(int j = 0; j < r; j++)
{
System.out.print(arr[j][i]+ " ");
}
System.out.println("\n");
}
}
}
```
```Output:
Enter rows and columns?
3 3
Enter integer elements of matrix
1 2 3
4 5 6
7 8 9
Transpose matrix:
1 4 7
2 5 8
3 6 9
```

In this program, sc.nextInt() statement has been used to accept entered int values from the keyboard. The nextInt() method is used to accept the next integer value from the Scanner.

In the nested for loops, one by one element is received by sc.nextInt() method and are initialized to the array arr[i][j].

Hope that this tutorial has covered almost all the important points related to multidimensional array in java with example program. I hope that you will have understood two dimensional array (2D array) in java with several types of example programs.

In the next tutorial, we will learn three dimensional array in java with example programs.