Next-Gen App & Browser Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

To multiply two matrices in Java, the number of columns in the first matrix must equal the number of rows in the second matrix. You then use three nested loops — the outer two loops select each cell of the result matrix, and the innermost loop computes the dot product by multiplying matching row-and-column elements and summing them. For two compatible matrices A (m x n) and B (n x p), the result C has dimensions m x p.
This guide walks through the dimension rule, the triple-nested-loop algorithm, two complete runnable programs (a hardcoded example and a Scanner-based version), a step-by-step output trace, the O(n^3) time complexity, and the bugs that trip up most beginners.
Matrix multiplication is not element-by-element like addition — if you need the simpler element-wise operation, see the companion guide on how to add two matrices in Java. Multiplication instead follows one strict compatibility rule that decides both whether two matrices can be multiplied and the shape of the result. Get this rule wrong and your program will either crash with an ArrayIndexOutOfBoundsException or quietly produce garbage.
The list below makes the dimension rule concrete with a few examples:
Each cell of the result matrix is a dot product: you take one row from the first matrix and one column from the second, multiply the matching elements, and add them up. The element at position C[i][j] is the sum of A[i][k] * B[k][j] for every index k across the shared dimension.
Translated into code, that requires exactly three loops, each with a clear job:
The pseudocode below captures the core idea before we move to a full program. Notice the accumulation operator += in the innermost line — that is what builds the dot product one term at a time.
for i in 0..rowsA:
for j in 0..colsB:
C[i][j] = 0
for k in 0..colsA: // colsA == rowsB
C[i][j] += A[i][k] * B[k][j]Here is a complete, runnable Java program that multiplies two hardcoded matrices using the three-nested-loop algorithm. A is a 2 x 3 matrix and B is a 3 x 2 matrix, so the result C is a 2 x 2 matrix. Copy it into a file named MatrixMultiply.java and run it as-is.
public class MatrixMultiply {
public static void main(String[] args) {
// Matrix A: 2 rows x 3 columns
int[][] a = {
{1, 2, 3},
{4, 5, 6}
};
// Matrix B: 3 rows x 2 columns
int[][] b = {
{7, 8},
{9, 10},
{11, 12}
};
int rowsA = a.length; // 2
int colsA = a[0].length; // 3 (shared dimension)
int colsB = b[0].length; // 2
// Result C: rowsA x colsB = 2 x 2 (auto-initialized to 0)
int[][] c = new int[rowsA][colsB];
// Triple nested loop: i = row, j = column, k = shared dimension
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
// Print the resultant matrix
System.out.println("Resultant Matrix:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}Running this prints a 2 x 2 result: 58 64 on the first row and 139 154 on the second. The key detail is the += operator — each result cell starts at zero (Java initializes a new int array to zeros automatically) and the inner loop adds each product term until the dot product is complete.
A production-quality version reads the dimensions and elements from the user with Scanner and, crucially, validates the dimension rule before multiplying. If the columns of the first matrix do not match the rows of the second, it prints a clear message and exits instead of crashing.
import java.util.Scanner;
public class MatrixMultiplyInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows and columns of first matrix: ");
int rowsA = sc.nextInt();
int colsA = sc.nextInt();
System.out.print("Enter rows and columns of second matrix: ");
int rowsB = sc.nextInt();
int colsB = sc.nextInt();
// Dimension-mismatch check: colsA must equal rowsB
if (colsA != rowsB) {
System.out.println("Multiplication not possible: columns of A ("
+ colsA + ") must equal rows of B (" + rowsB + ").");
sc.close();
return;
}
int[][] a = new int[rowsA][colsA];
int[][] b = new int[rowsB][colsB];
System.out.println("Enter elements of first matrix:");
for (int i = 0; i < rowsA; i++)
for (int j = 0; j < colsA; j++)
a[i][j] = sc.nextInt();
System.out.println("Enter elements of second matrix:");
for (int i = 0; i < rowsB; i++)
for (int j = 0; j < colsB; j++)
b[i][j] = sc.nextInt();
int[][] c = new int[rowsA][colsB];
for (int i = 0; i < rowsA; i++)
for (int j = 0; j < colsB; j++)
for (int k = 0; k < colsA; k++)
c[i][j] += a[i][k] * b[k][j];
System.out.println("Resultant Matrix:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}Notice the result matrix is sized rowsA x colsB — the outer dimensions — not colsA x colsB. Sizing the result wrong is one of the most frequent beginner errors, so always derive it from the rule A(m x n) * B(n x p) = C(m x p).
Let us trace the hardcoded example by hand so the loops stop feeling like magic. With A = {{1, 2, 3}, {4, 5, 6}} and B = {{7, 8}, {9, 10}, {11, 12}}, each result cell is the dot product of one row of A and one column of B:
So the program prints:
Resultant Matrix:
58 64
139 154Each value matches the inner loop's accumulation exactly. When i and j are fixed, the k loop runs three times — once per shared element — adding one product per pass until the dot product for that cell is complete.
The standard algorithm has a time complexity of O(n^3) for two n x n matrices. The reasoning is straightforward: there are n x n cells in the result, and computing each cell costs n multiply-and-add operations, giving n x n x n = n^3 total operations.
Multiplying two matrices in Java comes down to one rule and one pattern: the columns of the first matrix must match the rows of the second, and three nested loops compute the dot product for each result cell with the += accumulator. Validate dimensions up front, size the result as rowsA x colsB, and you have a correct, O(n^3) solution. Start from the hardcoded example to learn the mechanics, then move to the Scanner version for flexible, real-world input.
The number of columns in the first matrix must equal the number of rows in the second. If A is m x n, then B must be n x p, and the result C is m x p. If the rule is not met, multiplication is undefined and the program should reject the input.
The outer two loops walk every row and column of the result, selecting one cell at a time. The innermost loop computes that cell's dot product by multiplying matching row-and-column elements and summing them. Three loops are the minimum for the standard algorithm.
The standard triple-loop algorithm runs in O(n^3) for two n x n matrices, since each of the n-squared cells needs n multiplications. Space is O(n^2) for the result. Strassen's algorithm reduces this slightly but is rarely needed in practice.
Using = instead of += in the inner loop, which overwrites each cell instead of accumulating the dot product. Use c[i][j] += a[i][k] * b[k][j], and rely on Java zero-initializing a fresh int array so the sum starts at zero.
Yes. Non-square matrices multiply as long as the columns of the first equal the rows of the second. A 2 x 3 matrix can multiply a 3 x 4 matrix to give a 2 x 4 result. Only the inner dimensions must match; the outer dimensions set the result size.
The same triple-loop algorithm works for any sizes, as long as columns of A equal rows of B. Read both matrices with Scanner, check colsA == rowsB, size the result as rowsA x colsB, and let the k loop run over the shared dimension. The Scanner program above handles arbitrary sizes safely.
Yes, and it is cleaner. Move the loops into a method such as int[][] multiply(int[][] a, int[][] b) that returns the result matrix. This keeps main readable, makes the logic reusable, and lets you unit-test the multiplication in isolation from input and output code.
KaneAI - Testing Assistant
World’s first AI-Native E2E testing agent.

TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance