Matrix multiplication pairs each row of A with each column of B. If A is m × n and B is n × p, then AB exists and has size m × p.
Remember
A (m × n) × B (n × p) → C (m × p)
C[i][j] = sum over k of A[i][k] * B[k][j]
Example (2×2):
[1 2] [5 6] [1·5+2·7 1·6+2·8] [19 22]
[3 4] × [7 8] = [3·5+4·7 3·6+4·8] = [43 50]
Not the same as cell-by-cell multiply.
A shape
B shape
Allowed?
Result
2 × 2
2 × 2
Yes
2 × 2
2 × 3
3 × 2
Yes
2 × 2
2 × 3
2 × 2
No
—
Approach
How to Multiply Matrices in Java
Four clear steps — then code the classic triple loop.
Check that A’s columns equal B’s rows.
Create result C with size rowsA × colsB (zeros by default).
For each i, j, accumulate sum += A[i][k] * B[k][j] over k.
Store that sum in C[i][j].
Method
Idea
Time
Best for
Triple nested loops
Dot product of row i and column j
O(m × n × p)
Interviews, teaching
Shape-safe multiply
Validate inner dimensions first
O(m × n × p)
Safer production-style code
Pseudocode
Pseudocode
function Multiply(A, B):
m = rows of A
n = cols of A
p = cols of B
if n != rows of B:
error "inner dimensions must match"
C = new matrix[m][p] // zeros
for i from 0 to m - 1:
for j from 0 to p - 1:
for k from 0 to n - 1:
C[i][j] = C[i][j] + A[i][k] * B[k][j]
return C
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Shape rule
cols(A) == rows(B)
Result size
rows(A) × cols(B)
Cell formula
Σ A[i][k] * B[k][j]
Loops
i rows, j cols, k shared
Not entrywise
Do not confuse with A[i][j] * B[i][j]
Classic check
{{1,2},{3,4}} × {{5,6},{7,8}} = {{19,22},{43,50}}
Try it
Live Preview
Pick a sample pair to see A, B, and the product AB.
Tap a chip to run. Inner dimensions always match in these samples.
Result
A (2×2) =
1 2
3 4
B (2×2) =
5 6
7 8
A × B (2×2) =
19 22
43 50
Start with the classic triple nested loop. Then add an inner-dimension check for safer code.
Example 1 — Triple Nested Loops
Accumulate each result cell as a row-column dot product.
Java
public class MatrixMultiply {
static int[][] multiply(int[][] a, int[][] b) {
int m = a.length;
int n = a[0].length;
int p = b[0].length;
int[][] c = new int[m][p];
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < n; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
return c;
}
static void print(int[][] m) {
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] a = { { 1, 2 }, { 3, 4 } };
int[][] b = { { 5, 6 }, { 7, 8 } };
print(multiply(a, b));
}
}
Output
19 22
43 50
How It Works
m = rows of A, n = shared size, p = columns of B.
new int[m][p] starts filled with zeros — good for a running sum.
Outer i picks the result row; middle j picks the result column.
Inner k walks the shared dimension and adds a[i][k] * b[k][j].
For C[0][0]: 1*5 + 2*7 = 19.
Example 2 — Shape-Safe Multiply
Validate that A’s columns equal B’s rows before multiplying.
Java
public class MatrixMultiplySafe {
static int[][] multiply(int[][] a, int[][] b) {
int m = a.length;
int n = a[0].length;
int nB = b.length;
int p = b[0].length;
if (n != nB) {
throw new IllegalArgumentException(
"A columns (" + n + ") must equal B rows (" + nB + ").");
}
int[][] c = new int[m][p];
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < n; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
return c;
}
public static void main(String[] args) {
int[][] a = { { 1, 2, 3 }, { 4, 5, 6 } }; // 2×3
int[][] b = { { 7, 8 }, { 9, 10 }, { 11, 12 } }; // 3×2
int[][] c = multiply(a, b);
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[i].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
Output
58 64
139 154
How It Works
Compare a[0].length with b.length.
Throw if inner dimensions differ — multiplication is undefined.
Result size is 2 × 2 for a 2×3 times a 3×2.
Same triple loop accumulates each cell.
Check: C[0][0] = 1·7 + 2·9 + 3·11 = 58.
Edge Cases & Pitfalls
Check these before calling the solution done.
Inner dims
Must match
cols(A) == rows(B) or the product is undefined.
Entrywise
Wrong algorithm
Do not write A[i][j] * B[i][j] for true matrix multiply.
Order
AB ≠ BA
Multiplication is not commutative in general.
Overflow
Use long when needed
Products and sums can exceed Integer.MAX_VALUE.
Analysis
Time and Space Complexity
Program
Time
Extra space
Triple loops
O(m × n × p)
O(1) besides result
Shape-safe multiply
O(m × n × p)
O(1) besides result
For square n × n matrices the classic algorithm is O(n³). The result needs O(m × p) space.
Remember
Key Takeaways
Rule:cols(A) == rows(B); result is rows(A) × cols(B).