Java Program to multiply two matrices

We can multiply two matrices in java using binary * operator and executing another loop. A matrix is also known as array of arrays. We can add, subtract and multiply matrices.

In case of matrix multiplication, one row element of first matrix is multiplied by all columns of second matrix.

Matrix Multiplication in Java

Let’s see a simple example to multiply two matrices of 3 rows and 3 columns.

  1. public class MatrixMultiplicationExample{  
  2. public static void main(String args[]){  
  3. //creating two matrices    
  4. int a[][]={{1,1,1},{2,2,2},{3,3,3}};    
  5. int b[][]={{1,1,1},{2,2,2},{3,3,3}};    
  6.     
  7. //creating another matrix to store the multiplication of two matrices    
  8. int c[][]=new int[3][3];  //3 rows and 3 columns  
  9.     
  10. //multiplying and printing multiplication of 2 matrices    
  11. for(int i=0;i<3;i++){    
  12. for(int j=0;j<3;j++){    
  13. c[i][j]=0;      
  14. for(int k=0;k<3;k++)      
  15. {      
  16. c[i][j]+=a[i][k]*b[k][j];      
  17. }//end of k loop  
  18. System.out.print(c[i][j]+” “);  //printing matrix element  
  19. }//end of j loop  
  20. System.out.println();//new line    
  21. }    
  22. }}  

Output:

6 6 6 
12 12 12 
18 18 18 

Leave a Comment