0
0
JavaProgramBeginner · 2 min read

Java Program to Multiply Two Matrices

To multiply two matrices in Java, use nested for loops to calculate the sum of products of corresponding elements, like result[i][j] += matrix1[i][k] * matrix2[k][j] inside three loops iterating over rows and columns.
📋

Examples

Inputmatrix1 = {{1, 2}, {3, 4}}, matrix2 = {{5, 6}, {7, 8}}
Output{{19, 22}, {43, 50}}
Inputmatrix1 = {{2, 0}, {1, 3}}, matrix2 = {{1, 2}, {4, 0}}
Output{{2, 4}, {13, 2}}
Inputmatrix1 = {{0, 0}, {0, 0}}, matrix2 = {{1, 2}, {3, 4}}
Output{{0, 0}, {0, 0}}
🧠

How to Think About It

To multiply two matrices, think of each element in the result as the sum of products of elements from a row in the first matrix and a column in the second matrix. You use three loops: one for rows of the first matrix, one for columns of the second matrix, and one to multiply and sum the matching elements.
📐

Algorithm

1
Get the number of rows and columns of both matrices.
2
Check if the number of columns in the first matrix equals the number of rows in the second matrix.
3
Create a result matrix with rows of the first and columns of the second matrix.
4
Use three nested loops: outer for rows of first matrix, middle for columns of second matrix, inner for summing products.
5
Calculate each element of the result by summing products of corresponding elements.
6
Return or print the result matrix.
💻

Code

java
public class MatrixMultiplication {
    public static void main(String[] args) {
        int[][] matrix1 = {{1, 2}, {3, 4}};
        int[][] matrix2 = {{5, 6}, {7, 8}};
        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];
                }
            }
        }

        System.out.println("Result matrix:");
        for (int[] row : result) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}
Output
Result matrix: 19 22 43 50
🔍

Dry Run

Let's trace multiplying matrix1 = {{1, 2}, {3, 4}} and matrix2 = {{5, 6}, {7, 8}} through the code.

1

Initialize matrices and result

matrix1 = [[1, 2], [3, 4]], matrix2 = [[5, 6], [7, 8]], result = [[0, 0], [0, 0]]

2

Calculate result[0][0]

result[0][0] = (1*5) + (2*7) = 5 + 14 = 19

3

Calculate result[0][1]

result[0][1] = (1*6) + (2*8) = 6 + 16 = 22

4

Calculate result[1][0]

result[1][0] = (3*5) + (4*7) = 15 + 28 = 43

5

Calculate result[1][1]

result[1][1] = (3*6) + (4*8) = 18 + 32 = 50

ijkmatrix1[i][k]matrix2[k][j]Partial sum for result[i][j]
000155
0012719
010166
0112822
1003515
1014743
1103618
1114850
💡

Why This Works

Step 1: Matrix multiplication rule

Each element in the result matrix is the sum of products of elements from a row of the first matrix and a column of the second matrix using result[i][j] += matrix1[i][k] * matrix2[k][j].

Step 2: Nested loops for rows and columns

The outer two loops select the position i, j in the result matrix, and the inner loop sums the products over k.

Step 3: Result matrix size

The result matrix has the number of rows of the first matrix and the number of columns of the second matrix.

🔄

Alternative Approaches

Using a method to multiply matrices
java
public class MatrixMultiplication {
    public static int[][] multiply(int[][] m1, int[][] m2) {
        int rows1 = m1.length;
        int cols1 = m1[0].length;
        int cols2 = m2[0].length;
        int[][] res = 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++) {
                    res[i][j] += m1[i][k] * m2[k][j];
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[][] a = {{1, 2}, {3, 4}};
        int[][] b = {{5, 6}, {7, 8}};
        int[][] c = multiply(a, b);
        for (int[] row : c) {
            for (int val : row) System.out.print(val + " ");
            System.out.println();
        }
    }
}
Separates logic into a reusable method, improving readability and reusability.
Using streams (Java 8+)
java
import java.util.stream.IntStream;
public class MatrixMultiplication {
    public static void main(String[] args) {
        int[][] m1 = {{1, 2}, {3, 4}};
        int[][] m2 = {{5, 6}, {7, 8}};
        int rows1 = m1.length;
        int cols2 = m2[0].length;
        int cols1 = m1[0].length;
        int[][] result = new int[rows1][cols2];

        IntStream.range(0, rows1).forEach(i -> {
            IntStream.range(0, cols2).forEach(j -> {
                result[i][j] = IntStream.range(0, cols1)
                    .map(k -> m1[i][k] * m2[k][j])
                    .sum();
            });
        });

        for (int[] row : result) {
            for (int val : row) System.out.print(val + " ");
            System.out.println();
        }
    }
}
Uses Java streams for a functional style, but may be less readable for beginners.

Complexity: O(n * m * p) time, O(n * p) space

Time Complexity

The algorithm uses three nested loops: over rows of first matrix (n), columns of second matrix (p), and the shared dimension (m). This results in O(n * m * p) time.

Space Complexity

The result matrix requires space proportional to the number of rows of the first and columns of the second matrix, O(n * p). No extra large structures are used.

Which Approach is Fastest?

The basic triple loop is the standard and fastest for general cases. Stream-based approaches add overhead and are less efficient but can be more concise.

ApproachTimeSpaceBest For
Triple nested loopsO(n*m*p)O(n*p)General use, best performance
Method extractionO(n*m*p)O(n*p)Code reuse and clarity
Streams (Java 8+)O(n*m*p)O(n*p)Functional style, less performant
💡
Always check that the number of columns in the first matrix equals the number of rows in the second before multiplying.
⚠️
Trying to multiply matrices with incompatible sizes without checking dimensions first.