Multiply Two Matrices in Java
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.
Java Program
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
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.
- 1The guard
a[0].length != b.lengthrejects matrices whose inner dimensions don't match, since the product would be undefined. - 2The result
producttakes its row count from A and its column count from B. - 3The loops over
iandjpick a result cell; the innermost loop overkwalks the shared dimension. - 4
product[i][j] += a[i][k] * b[k][j]accumulates the dot product of rowiand columnj.
[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.
Why: Each of the r × c result cells needs n multiplications along the shared dimension, and only the result matrix is allocated.
Key Concepts
Approach 2: Cache-Friendly Loop Order (i-k-j)
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
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.
- 1The loop order becomes
i, thenk, thenj. - 2
factor = a[i][k]is read once and reused across the entire inner loop. - 3The inner loop adds
factor * b[k][j]intoproduct[i][j]for every column, walkingb[k]left to right. - 4After all
kvalues are processed, eachproduct[i][j]holds the same dot product as before.
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.
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
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.