Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Java Program to Multiply Two Matrices

To multiply two matrices in Java, the number of columns in the first matrix must equal the number of rows in the second matrix. You then use three nested loops — the outer two loops select each cell of the result matrix, and the innermost loop computes the dot product by multiplying matching row-and-column elements and summing them. For two compatible matrices A (m x n) and B (n x p), the result C has dimensions m x p.

This guide walks through the dimension rule, the triple-nested-loop algorithm, two complete runnable programs (a hardcoded example and a Scanner-based version), a step-by-step output trace, the O(n^3) time complexity, and the bugs that trip up most beginners.

Matrix Multiplication Rules

Matrix multiplication is not element-by-element like addition — if you need the simpler element-wise operation, see the companion guide on how to add two matrices in Java. Multiplication instead follows one strict compatibility rule that decides both whether two matrices can be multiplied and the shape of the result. Get this rule wrong and your program will either crash with an ArrayIndexOutOfBoundsException or quietly produce garbage.

  • The inner dimensions must match. To multiply A by B, the number of columns of A must equal the number of rows of B.
  • The result takes the outer dimensions. If A is m x n and B is n x p, the product C is m x p.
  • Order matters. Matrix multiplication is not commutative: A x B is generally not equal to B x A, and one direction may be valid while the other is not.

The list below makes the dimension rule concrete with a few examples:

  • Matrix A 2 x 3, Matrix B 3 x 2: valid (3 = 3), result C is 2 x 2.
  • Matrix A 3 x 3, Matrix B 3 x 3: valid (3 = 3), result C is 3 x 3.
  • Matrix A 2 x 3, Matrix B 2 x 3: not valid (3 not equal to 2), result C is undefined.
  • Matrix A 2 x 3, Matrix B 3 x 4: valid (3 = 3), result C is 2 x 4.

The Algorithm Explained

Each cell of the result matrix is a dot product: you take one row from the first matrix and one column from the second, multiply the matching elements, and add them up. The element at position C[i][j] is the sum of A[i][k] * B[k][j] for every index k across the shared dimension.

Translated into code, that requires exactly three loops, each with a clear job:

  • Outer loop (i) — iterates over every row of the result matrix.
  • Middle loop (j) — iterates over every column of the result matrix. Together, i and j pin down one result cell.
  • Inner loop (k) — walks the shared dimension, accumulating A[i][k] * B[k][j] into C[i][j].

The pseudocode below captures the core idea before we move to a full program. Notice the accumulation operator += in the innermost line — that is what builds the dot product one term at a time.

for i in 0..rowsA:
    for j in 0..colsB:
        C[i][j] = 0
        for k in 0..colsA:        // colsA == rowsB
            C[i][j] += A[i][k] * B[k][j]

Java Program to Multiply Two Matrices

Here is a complete, runnable Java program that multiplies two hardcoded matrices using the three-nested-loop algorithm. A is a 2 x 3 matrix and B is a 3 x 2 matrix, so the result C is a 2 x 2 matrix. Copy it into a file named MatrixMultiply.java and run it as-is.

public class MatrixMultiply {
    public static void main(String[] args) {

        // Matrix A: 2 rows x 3 columns
        int[][] a = {
            {1, 2, 3},
            {4, 5, 6}
        };

        // Matrix B: 3 rows x 2 columns
        int[][] b = {
            {7, 8},
            {9, 10},
            {11, 12}
        };

        int rowsA = a.length;       // 2
        int colsA = a[0].length;    // 3 (shared dimension)
        int colsB = b[0].length;    // 2

        // Result C: rowsA x colsB = 2 x 2 (auto-initialized to 0)
        int[][] c = new int[rowsA][colsB];

        // Triple nested loop: i = row, j = column, k = shared dimension
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                for (int k = 0; k < colsA; k++) {
                    c[i][j] += a[i][k] * b[k][j];
                }
            }
        }

        // Print the resultant matrix
        System.out.println("Resultant Matrix:");
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                System.out.print(c[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Running this prints a 2 x 2 result: 58 64 on the first row and 139 154 on the second. The key detail is the += operator — each result cell starts at zero (Java initializes a new int array to zeros automatically) and the inner loop adds each product term until the dot product is complete.

Program With User Input

A production-quality version reads the dimensions and elements from the user with Scanner and, crucially, validates the dimension rule before multiplying. If the columns of the first matrix do not match the rows of the second, it prints a clear message and exits instead of crashing.

import java.util.Scanner;

public class MatrixMultiplyInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter rows and columns of first matrix: ");
        int rowsA = sc.nextInt();
        int colsA = sc.nextInt();

        System.out.print("Enter rows and columns of second matrix: ");
        int rowsB = sc.nextInt();
        int colsB = sc.nextInt();

        // Dimension-mismatch check: colsA must equal rowsB
        if (colsA != rowsB) {
            System.out.println("Multiplication not possible: columns of A ("
                + colsA + ") must equal rows of B (" + rowsB + ").");
            sc.close();
            return;
        }

        int[][] a = new int[rowsA][colsA];
        int[][] b = new int[rowsB][colsB];

        System.out.println("Enter elements of first matrix:");
        for (int i = 0; i < rowsA; i++)
            for (int j = 0; j < colsA; j++)
                a[i][j] = sc.nextInt();

        System.out.println("Enter elements of second matrix:");
        for (int i = 0; i < rowsB; i++)
            for (int j = 0; j < colsB; j++)
                b[i][j] = sc.nextInt();

        int[][] c = new int[rowsA][colsB];
        for (int i = 0; i < rowsA; i++)
            for (int j = 0; j < colsB; j++)
                for (int k = 0; k < colsA; k++)
                    c[i][j] += a[i][k] * b[k][j];

        System.out.println("Resultant Matrix:");
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                System.out.print(c[i][j] + " ");
            }
            System.out.println();
        }
        sc.close();
    }
}

Notice the result matrix is sized rowsA x colsB — the outer dimensions — not colsA x colsB. Sizing the result wrong is one of the most frequent beginner errors, so always derive it from the rule A(m x n) * B(n x p) = C(m x p).

Step-by-Step Output Walkthrough

Let us trace the hardcoded example by hand so the loops stop feeling like magic. With A = {{1, 2, 3}, {4, 5, 6}} and B = {{7, 8}, {9, 10}, {11, 12}}, each result cell is the dot product of one row of A and one column of B:

  • C[0][0] = (1 x 7) + (2 x 9) + (3 x 11) = 7 + 18 + 33 = 58
  • C[0][1] = (1 x 8) + (2 x 10) + (3 x 12) = 8 + 20 + 36 = 64
  • C[1][0] = (4 x 7) + (5 x 9) + (6 x 11) = 28 + 45 + 66 = 139
  • C[1][1] = (4 x 8) + (5 x 10) + (6 x 12) = 32 + 50 + 72 = 154

So the program prints:

Resultant Matrix:
58 64
139 154

Each value matches the inner loop's accumulation exactly. When i and j are fixed, the k loop runs three times — once per shared element — adding one product per pass until the dot product for that cell is complete.

Time Complexity

The standard algorithm has a time complexity of O(n^3) for two n x n matrices. The reasoning is straightforward: there are n x n cells in the result, and computing each cell costs n multiply-and-add operations, giving n x n x n = n^3 total operations.

  • Time: O(m x p x n) in general, which simplifies to O(n^3) for square matrices.
  • Space: O(m x p) for the result matrix, i.e. O(n^2) for square inputs.
  • Faster algorithms exist — Strassen's runs in roughly O(n^2.81) — but they add complexity and are only worthwhile for very large matrices. For interviews and everyday code, the triple-loop O(n^3) version is the expected answer, and it shows up often in Java interview questions.

Common Mistakes and Troubleshooting

  • Dimension mismatch ignored — multiplying when columns of A do not equal rows of B causes an ArrayIndexOutOfBoundsException. Always validate colsA == rowsB before the loops.
  • Using = instead of += — writing c[i][j] = a[i][k] * b[k][j] overwrites the cell each pass and leaves only the last product. You must accumulate with += to build the dot product.
  • Wrong result size — sizing C as colsA x colsB instead of rowsA x colsB. The result rows come from A, the result columns come from B.
  • Wrong loop bound on k — the inner loop must run over the shared dimension (colsA, equal to rowsB), not over colsB. A wrong bound reads outside the array or skips terms.
  • Not resetting the accumulator — if you reuse a result array across runs, zero it first. A freshly allocated int[][] is already zero in Java, so prefer a new array per multiplication.

Conclusion

Multiplying two matrices in Java comes down to one rule and one pattern: the columns of the first matrix must match the rows of the second, and three nested loops compute the dot product for each result cell with the += accumulator. Validate dimensions up front, size the result as rowsA x colsB, and you have a correct, O(n^3) solution. Start from the hardcoded example to learn the mechanics, then move to the Scanner version for flexible, real-world input.

Frequently Asked Questions

What is the condition for multiplying two matrices in Java?

The number of columns in the first matrix must equal the number of rows in the second. If A is m x n, then B must be n x p, and the result C is m x p. If the rule is not met, multiplication is undefined and the program should reject the input.

Why do you need three nested loops to multiply matrices in Java?

The outer two loops walk every row and column of the result, selecting one cell at a time. The innermost loop computes that cell's dot product by multiplying matching row-and-column elements and summing them. Three loops are the minimum for the standard algorithm.

What is the time complexity of matrix multiplication in Java?

The standard triple-loop algorithm runs in O(n^3) for two n x n matrices, since each of the n-squared cells needs n multiplications. Space is O(n^2) for the result. Strassen's algorithm reduces this slightly but is rarely needed in practice.

What is the most common bug in a Java matrix multiplication program?

Using = instead of += in the inner loop, which overwrites each cell instead of accumulating the dot product. Use c[i][j] += a[i][k] * b[k][j], and rely on Java zero-initializing a fresh int array so the sum starts at zero.

Can you multiply non-square matrices in Java?

Yes. Non-square matrices multiply as long as the columns of the first equal the rows of the second. A 2 x 3 matrix can multiply a 3 x 4 matrix to give a 2 x 4 result. Only the inner dimensions must match; the outer dimensions set the result size.

How do you multiply two matrices of different sizes in Java?

The same triple-loop algorithm works for any sizes, as long as columns of A equal rows of B. Read both matrices with Scanner, check colsA == rowsB, size the result as rowsA x colsB, and let the k loop run over the shared dimension. The Scanner program above handles arbitrary sizes safely.

Can I use a method for matrix multiplication in Java?

Yes, and it is cleaner. Move the loops into a method such as int[][] multiply(int[][] a, int[][] b) that returns the result matrix. This keeps main readable, makes the logic reusable, and lets you unit-test the multiplication in isolation from input and output code.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests