Matrix Multiplication in Java
Multiply two matrices and print the result matrix.
- Time
O(r1 * c1 * c2), which is O(n^3) for two n x n matrices - Space
O(r1 * c2) for the result - Hints3
- Read3 min
To multiply two matrices in Java, use three nested loops. The first picks a row of A, the second picks a column of B, and the third adds up a[i][k] * b[k][j]. It only works when the number of columns in A equals the number of rows in B.
Problem statement
Write a matrix multiplication in Java program. You get matrix A and matrix B. Print A x B.
You can multiply them only if columns of A = rows of B. If A is 2 x 3 and B is
3 x 2, the answer is 2 x 2.
Matrix A of size r1 x c1 and matrix B of size r2 x c2.
The r1 x c2 product, one row per line.
Examples
A = [[1, 2, 3], [4, 5, 6]], B = [[7, 8], [9, 10], [11, 12]]58 64
139 154The first value is 1*7 + 2*9 + 3*11 = 58.
A = [[1, 2], [3, 4]], B = [[5, 6], [7, 8]]19 22
43 50The first value is 1*5 + 2*7 = 19.
Constraints
- 1 <= rows, columns <= 200
- c1 must equal r2
- Every result fits in an int
Think before you code
Reveal the questions to ask yourself first
- Which row and which column make the value at row 0, column 1 of the answer?
- How many rows and columns will the answer have?
- What should happen if the sizes do not match?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- Check that the columns of A equal the rows of B.
- Make a result array with
rows of Aandcolumns of B. - For every row
iof A and every columnjof B, startsumat 0. - Loop
kover the shared size and adda[i][k] * b[k][j]. - Store
suminresult[i][j].
A handy way to remember it: row into column, multiply, then add. If 2D arrays are new to you, read arrays in Java and loops first.
Dry run
Walk through the example step by step
A is [[1, 2, 3], [4, 5, 6]] and B is [[7, 8], [9, 10], [11, 12]]:
cell | row of A | column of B | work | value
-------+----------+-------------+-------------------+------
[0][0] | 1 2 3 | 7 9 11 | 7 + 18 + 33 | 58
[0][1] | 1 2 3 | 8 10 12 | 8 + 20 + 36 | 64
[1][0] | 4 5 6 | 7 9 11 | 28 + 45 + 66 | 139
[1][1] | 4 5 6 | 8 10 12 | 32 + 50 + 72 | 154
Solution
Reveal the full Java solution
public class MatrixMultiplication {
public static int[][] multiply(int[][] a, int[][] b) {
int rows = a.length;
int common = b.length;
int cols = b[0].length;
if (a[0].length != common) {
throw new IllegalArgumentException(
"Columns of A must equal rows of B");
}
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int sum = 0;
for (int k = 0; k < common; k++) {
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
return result;
}
public static void print(int[][] m) {
for (int[] row : m) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] a = {{1, 2, 3}, {4, 5, 6}};
int[][] b = {{7, 8}, {9, 10}, {11, 12}};
print(multiply(a, b));
// 58 64
// 139 154
}
}This is the matrix multiplication in Java simple program: the values are fixed, so you can run it at once. The two outer loops choose the cell. The inner loop does the adding.
Matrix multiplication in Java using Scanner
This version is matrix multiplication in Java with user input. It asks for the sizes first and stops early if they do not match.
import java.util.Scanner;
public class MatrixScanner {
static int[][] read(Scanner sc, int rows, int cols) {
int[][] m = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = sc.nextInt();
}
}
return m;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Rows and columns of A:");
int r1 = sc.nextInt(), c1 = sc.nextInt();
System.out.println("Rows and columns of B:");
int r2 = sc.nextInt(), c2 = sc.nextInt();
if (c1 != r2) {
System.out.println("Cannot multiply: " + c1 + " != " + r2);
return;
}
System.out.println("Enter A, then B:");
int[][] a = read(sc, r1, c1);
int[][] b = read(sc, r2, c2);
int[][] result = new int[r1][c2];
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
result[i][j] += a[i][k] * b[k][j];
}
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
For sizes 2 2 and 2 2, then A = 1 2 3 4 and B = 5 6 7 8, the result part prints:
19 22
43 50
For sizes 2 3 and 2 2 it prints Cannot multiply: 3 != 2.
Simple changes to the matrix multiplication in Java code
- Use
longfor the sum if the numbers are large. - In this Scanner version you can swap the
jandkloops and print afterwards. The answer is the same, and large matrices often run faster because memory is read row by row.
Next, try the transpose of a matrix, build the Pascal triangle, or join a Java full stack course for guided practice.
O(r1 * c1 * c2), which is O(n^3) for two n x n matricesO(r1 * c2) for the resultReview before the interview
Common mistakes
- Multiplying cell by cell, a[i][j] * b[i][j]. That is a different operation.
- Making the result with the wrong size. It needs rows of A and columns of B.
- Not setting sum back to 0 for each new cell.
Edge cases to test
- Sizes that do not match, such as 2 x 3 and 2 x 2, must be rejected.
- A 1 x n matrix times an n x 1 matrix gives one single value.
- Multiplying by the identity matrix must return the same matrix.
Interview follow-ups
- Why is A x B usually not equal to B x A?
- How would you raise a square matrix to the power p?
- What is Strassen's algorithm trying to reduce?
Keep practising
Find the Sum of All Elements in an Array
Hints · Dry run · SolutionSolve Similar problemFind the Average of the Elements in an Array
Hints · Dry run · SolutionSolve Similar problemFind a Pair With a Given Sum in an Array
Hints · Dry run · SolutionSolve Related learningArrays
TutorialLearn Related learningLoops
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
