Perform Matrix Multiplication in Java
What you’ll learn
- The row × column rule: each value of
ABis a dot product of one row ofAand one column ofB. - 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[][] matrixand nestedforloops. - You know that for
A (m×n)andB (n×p), the inner valuenmust 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].
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.
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
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]Multiply two 3×3 matrices
This Java version mirrors the classic 3×3 interview example and prints the same result matrix.
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);
}
}Smaller 2×2 product (easy to verify)
A compact Java example with the same triple-loop logic.
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
🔄 Input / output examples
| Case | Result |
|---|---|
2x2 by 2x2 | Valid multiplication |
2x3 by 2x2 | Invalid (inner dimensions mismatch) |
Edge cases
Inner dimensions must match
You cannot multiply m×n by p×q unless n = p.
AB is usually not BA
Matrix multiplication is not commutative in general.
Large products
For large values, int may overflow. Use long when needed.
⏱️ Time and space complexity
| Setting | Time | Extra space |
|---|---|---|
Two n × n matrices, classic triple loop | O(n3) | O(1) beyond output matrix |
m×n by n×p | O(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.
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.
8 people found this page helpful
