Java Code to Perform Matrix Multiplication

In Java, matrix multiplication can be accomplished using the binary “*” operator along with an additional loop. A matrix also referred to as an array of arrays, allows for various operations such as addition, subtraction, and multiplication.

During matrix multiplication, each element of a row in the first matrix is multiplied by all the corresponding elements in the columns of the second matrix.

Java Code to Perform Matrix Multiplication

public class MatrixMultiplicationExample{  
public static void main(String args[]){  
//creating two matrices    
int a[][]={{1,1,1},{2,2,2},{3,3,3}};    
int b[][]={{1,1,1},{2,2,2},{3,3,3}};    
    
//creating another matrix to store the multiplication of two matrices    
int c[][]=new int[3][3];  //3 rows and 3 columns  
    
//multiplying and printing multiplication of 2 matrices    
for(int i=0;i<3;i++){    
for(int j=0;j<3;j++){    
c[i][j]=0;      
for(int k=0;k<3;k++)      
{      
c[i][j]+=a[i][k]*b[k][j];      
}//end of k loop  
System.out.print(c[i][j]+" ");  //printing matrix element  
}//end of j loop  
System.out.println();//new line    
}    
}}

Output:

6 6 6 
12 12 12 
18 18 18
In conclusion, the provided Java code effectively performs matrix multiplication by iterating through each element of the resulting matrix and calculating the dot product of corresponding rows and columns from the input matrices, producing the desired matrix multiplication output. Follow tutorials.freshersnow.com to learn more.