Perform Matrix Multiplication in Java

Beginner
⏱️ 12 min read
📚 Updated: May 2026
🎯 2 Code Examples
Java + linear algebra

What you’ll learn

  • The row × column rule: each value of AB is a dot product of one row of A and one column of B.
  • Why three nested loops are used, and why result cells should start from zero before adding products.
  • A full 3×3 Java program, a smaller 2×2 example, and a live preview to verify output quickly.

Prerequisites

Nested loops, 2D arrays, and the matrix size rule for valid multiplication.

  • Basics of Java arrays like int[][] matrix and nested for loops.
  • You know that for A (m×n) and B (n×p), the inner value n must match.

Formula

If A is m×n and B is n×p, then C = AB is m×p and each cell is C[i][j] = ∑k A[i][k] * B[k][j].

Square-matrix examples used here

The two Java programs use 3×3 and 2×2 matrices so you can trace each multiplication step easily.

Trace one cell

For the 3×3 sample, first result cell is row 0 of A and column 0 of B: 1·9 + 2·6 + 3·3 = 30.

Live preview

Uses the same 3×3 matrices as example 1. Press the button to see the product.

JavaScript output here matches the Java sample math.

Live result
Press "Show 3×3 product".

Algorithm

Goal: compute C = AB for compatible matrices. In the examples below, we use square matrices for easier understanding.

Check dimensions

For A (m×n) and B (n×p), the inner values n must match.

Use triple loop

For each result cell C[i][j], add A[i][k] * B[k][j] for all k.

Display result

Print both input matrices and the final product matrix clearly row by row.

📜 Pseudocode

Pseudocode
function multiply(A, B, C, rowsA, colsA, colsB):
    for i from 0 to rowsA - 1:
        for j from 0 to colsB - 1:
            C[i][j] = 0
            for k from 0 to colsA - 1:
                C[i][j] = C[i][j] + A[i][k] * B[k][j]
1

Multiply two 3×3 matrices

This Java version mirrors the classic 3×3 interview example and prints the same result matrix.

java
public class Main {
    static final int N = 3;

    static void multiplyMatrices(int[][] a, int[][] b, int[][] result) {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                result[i][j] = 0;
                for (int k = 0; k < N; k++) {
                    result[i][j] += a[i][k] * b[k][j];
                }
            }
        }
    }

    static void displayMatrix(int[][] matrix) {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] firstMatrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        int[][] secondMatrix = {
            {9, 8, 7},
            {6, 5, 4},
            {3, 2, 1}
        };
        int[][] result = new int[N][N];

        multiplyMatrices(firstMatrix, secondMatrix, result);

        System.out.println("First Matrix:");
        displayMatrix(firstMatrix);
        System.out.println("\nSecond Matrix:");
        displayMatrix(secondMatrix);
        System.out.println("\nResult Matrix:");
        displayMatrix(result);
    }
}
2

Smaller 2×2 product (easy to verify)

A compact Java example with the same triple-loop logic.

java
public class Main {
    static final int N = 2;

    static void multiplyMatrices(int[][] a, int[][] b, int[][] result) {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                result[i][j] = 0;
                for (int k = 0; k < N; k++) {
                    result[i][j] += a[i][k] * b[k][j];
                }
            }
        }
    }

    static void printMatrix(String title, int[][] matrix) {
        System.out.println(title);
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] a = {
            {1, 2},
            {3, 4}
        };
        int[][] b = {
            {5, 6},
            {7, 8}
        };
        int[][] r = new int[N][N];

        multiplyMatrices(a, b, r);

        printMatrix("A", a);
        System.out.println();
        printMatrix("B", b);
        System.out.println();
        printMatrix("AB", r);
    }
}

Optimization notes

Classic triple loop is standard; for large matrices, blocked multiplication improves cache usage.

❓ FAQ

The number of columns of A must equal the number of rows of B. If A is m×n and B is n×p, then AB exists and is m×p.
No. Standard matrix multiplication uses row-column dot products. Element-wise multiplication is a different operation.
i loops over rows of result, j loops over columns of result, and k accumulates A[i][k] * B[k][j].
Each result cell is built by adding many products, so it must start from zero.
Large values can overflow int. Use long or BigInteger when the problem needs larger ranges.
Classic triple-loop multiplication takes O(n^3) time for square matrices.

🔄 Input / output examples

CaseResult
2x2 by 2x2Valid multiplication
2x3 by 2x2Invalid (inner dimensions mismatch)

Edge cases

Shape

Inner dimensions must match

You cannot multiply m×n by p×q unless n = p.

Order

AB is usually not BA

Matrix multiplication is not commutative in general.

Overflow

Large products

For large values, int may overflow. Use long when needed.

⏱️ Time and space complexity

SettingTimeExtra space
Two n × n matrices, classic triple loopO(n3)O(1) beyond output matrix
m×n by n×pO(m · n · p)O(1) beyond output matrix

Summary

  • Matrix multiplication follows row-by-column dot products.
  • Inner dimensions must match for multiplication to exist.
Did you know?

Matrix multiplication links rows of A with columns of B. If A is m × n and B is n × p, then AB is m × p.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful