Java program to multiply two matrices

Let’s learn java program to multiply two matrices.

Java program to multiply two matrices

java program to multiply two matrices

Matrix multiplication in java is performed by multiplying row element of first matrix by all columns of second matrix.

In java, to perform matrix multiplication binary operator ” * ” is used.

Also read – matrix transpose in java

Also first matrix column should be equal to second matrix row. In the below matrix multiplication we are using Scanner class to enter number of rows, columns and elements of matrix.

Let’s see java program to perform matrix multiplication,

import java.util.Scanner;

public class MatrixMultiplicationInJava 
{
   public static void main(String[] args) 
   { 
      int row, column, a, b, total = 0, x, y, z;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter no. of rows and columns : ");
      row = sc.nextInt();
      column = sc.nextInt();

      int matrix1[][] = new int[row][column];
      System.out.println("Please enter elements of matrix1 : ");
      for(x = 0; x < row; x++)
      {
         for(y = 0; y < column; y++)
         {
            matrix1[x][y] = sc.nextInt();
         }
      } 
      System.out.println("Please enter no. of rows and columns : ");
      a = sc.nextInt();
      b = sc.nextInt();

      if(column != a)
      {
         System.out.println("Matrices can't be multiplied!!");
      }
      else
      {
         int matrix2[][] = new int[a][b];
         int multiply[][] = new int[row][b];
         System.out.println("Please enter elements of matrix2 : ");
         for(x = 0; x < a; x++)
         {
            for(y = 0; y < b; y++)
            {
               matrix2[x][y] = sc.nextInt();
            }
         } 
         for(x = 0; x < row; x++)
         {
            for(y = 0; y < b; y++)
            { 
               for(z = 0; z < a; z++)
               {
                  total = total + matrix1[x][z] * matrix2[z][y];
               }
               multiply[x][y] = total;
               total = 0;
            }
         }

         System.out.println("Multiplication of matrices : ");
         for(x = 0; x < row; x++)
         {
            for(y = 0; y < b; y++)
            {
               System.out.print(multiply[x][y] + "\t");
            }
            System.out.print("\n");
         }
      }
      sc.close();
   }
}



Output:

Please enter no. of rows and columns : 3 3
Please enter elements of matrix1 :
2 4 6
8 2 4
6 8 2
Please enter no. of rows and columns : 3 3
Please enter elements of matrix2 :
1 3 5
7 9 1
3 5 7
Multiplication of matrices :
48 72 56
34 62 70
68 100 52

Also read – matrix multiplication in java using methods