Two Dimensional Array in Java: Usage and Examples

Rumman Ansari   Software Engineer   2024-07-05 04:09:18   7060  Share
Subject Syllabus DetailsSubject Details 2 Program
☰ TContent
☰Fullscreen

Table of Content:

A multi-dimensional array is very much similar to a single dimensional array. It can have multiple rows and multiple columns unlike single dimensional array, which can have only one full row or one full column.

Syntax to Declare Multidimensional Array in java

 datatype[ ][ ] identifier;
or
datatype identifier[ ][ ];
 
 
dataType[][] arrayRefVarName; (or)  
dataType [][]arrayRefVarName; (or)  
dataType arrayRefVarName[][]; (or)  
dataType []arrayRefVarName[];    
 

Initialization of Array

new operator is used to initialize an array.

Example:

int[ ][ ] arrName = new int[10][10];    //10 by 10 is the size of array.
or
int[ ][ ] arrName = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
// 3 by 5 is the size of the array.
 

Accessing array element

For both, row and column, the index begins from 0.

Syntax:

array_name[m-1][n-1]

Example:

int arr[ ][ ] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
System.out.println("Element at (2,3) place" + arr[1][2]);

Example to instantiate Multidimensional Array in java

 
int[][] arrName=new int[3][3];//3 row and 3 column 

Example to initialize Multidimensional Array in java

arrName[0][0]=1;  
arrName[0][1]=2;  
arrName[0][2]=3;  
arrName[1][0]=4;  
arrName[1][1]=5;  
arrName[1][2]=6;  
arrName[2][0]=7;  
arrName[2][1]=8;  
arrName[2][2]=9;  

Example of Multidimensional java array

Program: Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

class Arrayxample{
public static void main(String args[]){

//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

 //printing 2D array
 for(int i=0;i<3;i++){
   for(int j=0;j<3;j++){
     System.out.print(arr[i][j]+" ");
  }
  System.out.print("\n");
 }

 }
}

Output:

1 2 3
2 4 5
4 4 5
Press any key to continue . . .

Java Programming Code for Two Dimensional (2D) Array

Following Java Program ask to the user to enter row and column size of the array then ask to the user to enter the array elements, and the program will display the two dimensional array:


/* Java Program Example - Two Dimensional Array */

import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
       int row, col, i, j;
       int arr[][] = new int[10][10];
       Scanner scan = new Scanner(System.in);

       System.out.print("Enter Number of Row for Array (max 10) : ");
       row = scan.nextInt();
       System.out.print("Enter Number of Column for Array (max 10) : ");
       col = scan.nextInt();

       System.out.println("Enter " +(row*col)+ " Array Elements : ");
       for(i=0; i<row; i++)
       {
           for(j=0; j<col; j++)
           {
               arr[i][j] = scan.nextInt();
           }
       }

       System.out.print("The Array is :\n");
       for(i=0; i<row; i++)
       {
           for(j=0; j<col; j++)
           {
               System.out.print(arr[i][j]+ "  ");
           }
           System.out.println();
       }
   }
}

Output

When the above Java Program is compile and executed, it will produce the following output:

Enter Number of Row for Array (max 10) : 3
Enter Number of Column for Array (max 10) : 3
Enter 9 Array Elements :
1
2
3
4
5
6
7
8
9
The Array is :
1  2  3
4  5  6
7  8  9
Press any key to continue . . .

Addition of two matrices in java

Program: Let's see a simple example that adds two matrices.

class ArrayEx{
public static void main(String args[]){
	//creating two matrices
	int a[][]={{2,4,6},{3,4,5}};
	int b[][]={{7,1,2},{2,1,5}};

	//creating another matrix to store the sum of two matrices
	int c[][]=new int[2][3];

	//adding and printing addition of two matrices
	for(int i=0;i<2;i++){
		for(int j=0;j<3;j++){
			c[i][j]=a[i][j]+b[i][j];
			System.out.print(c[i][j]+" ");
		}
		System.out.println();//new line
	}

	}
}

Output:

9 5 8
5 5 10
Press any key to continue . . .

Program to multiply two matrices

Program: Let's see a simple example that multiply two matrices.

This java program multiply two matrices. Before multiplication matrices are checked whether they can be multiplied or not.


import java.util.Scanner;

class MatrixMultiplication
{
   public static void main(String args[])
   {
      int m, n, p, q, sum = 0, c, d, k;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of rows and columns of first matrix");
      m = in.nextInt();
      n = in.nextInt();

      int first[][] = new int[m][n];

      System.out.println("Enter the elements of first matrix");

      for ( c = 0 ; c < m ; c++ )
         for ( d = 0 ; d < n ; d++ )
            first[c][d] = in.nextInt();

      System.out.println("Enter the number of rows and columns of second matrix");
      p = in.nextInt();
      q = in.nextInt();

      if ( n != p )
         System.out.println("Matrices with entered orders can't be multiplied with each other.");
      else
      {
         int second[][] = new int[p][q];
         int multiply[][] = new int[m][q];

         System.out.println("Enter the elements of second matrix");

         for ( c = 0 ; c < p ; c++ )
            for ( d = 0 ; d < q ; d++ )
               second[c][d] = in.nextInt();

         for ( c = 0 ; c < m ; c++ )
         {
            for ( d = 0 ; d < q ; d++ )
            {
               for ( k = 0 ; k < p ; k++ )
               {
                  sum = sum + first[c][k]*second[k][d];
               }

               multiply[c][d] = sum;
               sum = 0;
            }
         }

         System.out.println("Product of entered matrices:-");

         for ( c = 0 ; c < m ; c++ )
         {
            for ( d = 0 ; d < q ; d++ )
               System.out.print(multiply[c][d]+"\t");

            System.out.print("\n");
         }
      }
   }
}

Output:

Enter the number of rows and columns of first matrix
3 3
Enter the elements of first matrix
1 2 3
4 5 6
7 8 9
Enter the number of rows and columns of second matrix
3 3
Enter the elements of second matrix
9 8 7
6 5 4
3 2 1
Product of entered matrices:-
30      24      18
84      69      54
138     114     90
Press any key to continue . . .