Java Programs›Arrays›Multiply Two Matrices

Multiply Two Matrices in Java

intermediate·  Arrays  ·  Matrix

Problem

Multiplying an r × n matrix by an n × c matrix gives an r × c result, where each cell is the sum of products of one row from the first matrix and one column from the second.

Given a matrix A with as many columns as matrix B has rows, compute the product A × B.

Input
A = [[2, 0, 1], [3, 4, 2]], B = [[1, 5], [2, 0], [6, 3]]
Output
[[8, 13], [23, 21]]

Java Program

Java
import java.util.Arrays; public class MultiplyTwoMatrices { public static void main(String[] args) { int[][] a = {{2, 0, 1}, {3, 4, 2}}; // 2 x 3 int[][] b = {{1, 5}, {2, 0}, {6, 3}}; // 3 x 2 if (a[0].length != b.length) { System.out.println("Cannot multiply: columns of A must equal rows of B"); return; } int rows = a.length; int cols = b[0].length; int shared = b.length; int[][] product = new int[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { for (int k = 0; k < shared; k++) { product[i][j] += a[i][k] * b[k][j]; // row i of A paired with column j of B } } } for (int[] row : product) { System.out.println(Arrays.toString(row)); } } }

Output

[8, 13] [23, 21]

Core Logic

Every result cell is a small dot product — walk along row i of A and down column j of B at the same time, multiplying the pairs and adding them up.

How It Works
  1. 1The guard a[0].length != b.length rejects matrices whose inner dimensions don't match, since the product would be undefined.
  2. 2The result product takes its row count from A and its column count from B.
  3. 3The loops over i and j pick a result cell; the innermost loop over k walks the shared dimension.
  4. 4product[i][j] += a[i][k] * b[k][j] accumulates the dot product of row i and column j.
For cell [1][0], row 1 of A is [3, 4, 2] and column 0 of B is [1, 2, 6], so the value is 3×1 + 4×2 + 2×6 = 23.
💡

Key Point: Matrix multiplication is not commutative — here A × B is 2 × 2, while B × A would be a 3 × 3 matrix with entirely different values.

Complexity
Time Complexity: O(r × c × n)Space Complexity: O(r × c)

Why: Each of the r × c result cells needs n multiplications along the shared dimension, and only the result matrix is allocated.

Key Concepts

2D arraytriple nested loopdot productcompound assignment

Approach 2: Cache-Friendly Loop Order (i-k-j)

Java
import java.util.Arrays; public class MultiplyTwoMatricesIkj { public static void main(String[] args) { int[][] a = {{2, 0, 1}, {3, 4, 2}}; // 2 x 3 int[][] b = {{1, 5}, {2, 0}, {6, 3}}; // 3 x 2 int rows = a.length; int cols = b[0].length; int shared = b.length; int[][] product = new int[rows][cols]; for (int i = 0; i < rows; i++) { for (int k = 0; k < shared; k++) { int factor = a[i][k]; // read once, reused across a whole row of B for (int j = 0; j < cols; j++) { product[i][j] += factor * b[k][j]; // walks B row by row, the way it sits in memory } } } for (int[] row : product) { System.out.println(Arrays.toString(row)); } } }

Output

[8, 13] [23, 21]

Core Logic

Swapping the two inner loops gives exactly the same sums but reads matrix B along its rows instead of down its columns, which suits how Java lays arrays out in memory.

How It Works
  1. 1The loop order becomes i, then k, then j.
  2. 2factor = a[i][k] is read once and reused across the entire inner loop.
  3. 3The inner loop adds factor * b[k][j] into product[i][j] for every column, walking b[k] left to right.
  4. 4After all k values are processed, each product[i][j] holds the same dot product as before.
With i = 1 and k = 2, factor is 2, and the inner loop adds 2×6 to product[1][0] and 2×3 to product[1][1] in one sweep.
💡

Key Point: In Java each row of a 2D array is its own contiguous array, so reading b[k][j] with j moving fastest touches memory in order — on large matrices this is noticeably faster, even though the Big-O is unchanged.

Complexity
Time Complexity: O(r × c × n)Space Complexity: O(r × c)

Why: The same r × c × n multiply-adds are performed; only their order changes, which improves memory locality rather than the operation count.

Key Concepts

loop reorderingrow-major accessCPU cache

Interview Questions

When can two matrices be multiplied?

When the number of columns in the first equals the number of rows in the second. A 2×3 matrix can be multiplied by a 3×2 matrix, giving a 2×2 result.

Is matrix multiplication commutative?

No. A × B and B × A usually differ, and one of them may not even be defined.

Learn the Concept

Related Programs