Home >>Java Programs >Java Program to find the product of two matrices

# Java Program to find the product of two matrices

### Java Program to find the product of two matrices

In this example, we will create a java program to multiply two matrices and print the resulting matrix.

Product of two matrices can be found by multiplying the elements of each row of the first matrix with the corresponding column of the second matrix then add all the product of elements.

##### Program:
``````
public class Main
{
public static void main(String[] args)
{
int row1, col1, row2, col2;
int a[][] = {
{1, 3, 2},
{5, 2, 1},
{1, 2, 3}
};
int b[][] = {
{2, 1, 4},
{5, 0, 1},
{1, 2, 6}
};
row1 = a.length;
col1 = a[0].length;
row2 = b.length;
col2 = b[0].length;
if(col1 != row2){
System.out.println("Matrices cannot be multiplied");
}
else{
int prod[][] = new int[row1][col2];
for(int i = 0; i < row1; i++){
for(int j = 0; j < col2; j++){
for(int k = 0; k < row2; k++){
prod[i][j] = prod[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("Product of two matrices: ");
for(int i = 0; i < row1; i++){
for(int j = 0; j < col2; j++){
System.out.print(prod[i][j] + " ");
}
System.out.println();
}
}
}
}
```
```
Output
Product of two matrices:
19 5 19
21 7 28
15 7 24