Java program to multiply two matrices

Let’s learn 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.

Also read – matrix transpose in java

To perform matrix multiplication binary operator * is used.

java program to multiply two matrices

Let’s see program to multiply two matrices.

import java.util.Scanner;
public class MatrixMultiplicationInJava
{
   public static void main(String[] args)
   {
      int[][] matrixOne = {{1,3,5},{2,4,6},{1,1,1}};    
      int[][] matrixTwo = {{2,4,6},{1,1,1},{1,3,5}};	    
      // matrix to store the multiplication    
      int[][] multiply = new int[3][3];	    
      // multiplying and printing 2 matrices
      System.out.println("Multiplication of two matrices: ");
      for(int a = 0; a < 3; a++)
      {    
         for(int b = 0; b < 3; b++)
         {    
            multiply[a][b] = 0;      
            for(int c = 0; c < 3; c++)      
            {   
               multiply[a][b] += matrixOne[a][c] * matrixTwo[c][b];      
            }  
            System.out.print(multiply[a][b] + " ");  
         }  
         System.out.println();
      }
   }
}


Output:

Multiplication of two matrices:
10 22 34
14 30 46
4 8 12


Also read – matrix multiplication in java using methods

Also read – matrix multiplication in java with scanner