Google News
logo
Java Program to Multiply Two Matrices
In the following examples of Java program to multiply two matrices :
Program :
public class MatrixMultiplication {
    public static void main(String[] args) {
        int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] matrix2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
        int[][] resultMatrix = multiplyMatrices(matrix1, matrix2);

        System.out.println("Matrix 1:");
        printMatrix(matrix1);
        System.out.println("Matrix 2:");
        printMatrix(matrix2);
        System.out.println("Result Matrix:");
        printMatrix(resultMatrix);
    }

    public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {
        int rows1 = matrix1.length;
        int cols1 = matrix1[0].length;
        int cols2 = matrix2[0].length;

        int[][] result = new int[rows1][cols2];

        for (int i = 0; i < rows1; i++) {
            for (int j = 0; j < cols2; j++) {
                for (int k = 0; k < cols1; k++) {
                    result[i][j] += matrix1[i][k] * matrix2[k][j];
                }
            }
        }

        return result;
    }

    public static void printMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output :
Matrix 1:
1 2 3 
4 5 6 
7 8 9 
Matrix 2:
9 8 7 
6 5 4 
3 2 1 
Result Matrix:
30 24 18 
84 69 54 
138 114 90 
In this program, we have two matrices matrix1 and matrix2, which are multiplied to produce a third matrix resultMatrix. The matrices are represented as two-dimensional arrays.

We define a method multiplyMatrices that takes two matrices as input and returns their product. We first calculate the number of rows and columns of the resulting matrix, which are the same as the rows of the first matrix and the columns of the second matrix, respectively.

We then define a new two-dimensional array result with the appropriate size. We use three nested loops to calculate each element of the resulting matrix.

Finally, we define a method printMatrix to print a matrix to the console.