Matrix Multiplication in Java: Code, Rules & Faster Methods

Multiplying Matrices in Java: A Step-by-Step Guide

"Multiplying matrices in Java" is a fundamental operation in linear algebra, and it is used in many fields, like computer graphics, data analysis, and scientific computing. In this article, we'll explore how to multiply matrices in Java. We will break down the process into easy-to-follow steps, provide Java code, and explain each step in detail.

We will also look at the parts most tutorials skip: what happens when the sizes don't match, why the order of your loops made our program about 6 times faster, and the small bugs that give wrong answers without any error.

So, let us dive into today's topic without waiting any further!

TL;DR: Multiplying Matrices In Java

AspectSummary
Matrix BasicsMatrices are stored as 2D arrays in Java, like int[][], and are used for operations like addition, subtraction, and multiplication.
Multiplication RuleTwo matrices can be multiplied only if the number of columns of matrix A equals the number of rows of matrix B. The result has the size rows(A) x columns(B).
Dot Product LogicEach cell of the result is the dot product of one row of A and one column of B: multiply the matching elements and add them up.
Java ImplementationThree nested loops: i for the rows of A, j for the columns of B, and k for the shared dimension.
Steps Of ImplementationTake the dimensions, check that they can be multiplied, read the elements, run the triple loop, and print the result.

Introduction To Matrices & Matrix Multiplication

Matrices are mathematical structures that store numbers in a rectangular grid. Just like a table, they have rows and columns. They are used not only in mathematics but also in physics and computer science for many purposes.

Introduction to matrices showing rows and columns of a matrix

Since they hold numbers, we can perform various operations on them as well. Some of these operations are:

  • Matrix addition
  • Matrix subtraction
  • Matrix multiplication
  • Transpose of a matrix

In this article, we will focus on multiplying matrices. Once we learn the steps for multiplication, we will do it using the Java programming language. The sections below walk through each step, so keep reading!

Just like regular multiplication, in matrix multiplication, two matrices are multiplied to produce a new matrix. But it does not work cell by cell. Instead, every cell of the new matrix is the dot product of a row from the first matrix and a column from the second matrix.

However, not all matrices can be multiplied. To multiply two matrices, they must meet the following conditions.

To multiply 2 matrices:

  • The number of columns in the first matrix must be equal to the number of rows in the second matrix.
  • The product matrix will have the number of rows of the first matrix and the number of columns of the second matrix.

This means:

Matrix 1 [m1 x n1] * Matrix 2 [m2 x n2] = Matrix 3 [m1 x n2], where n1 = m2

Understanding Matrix Multiplication: Rules And Formula

As we discussed above, while multiplying matrices, we need to keep two things in mind: the condition for multiplication and the size of the product matrix. Let us understand these with the help of an example.

Let us consider two matrices:

  • Matrix A has the dimensions 2 x 3.
  • Matrix B has the dimensions 3 x 4.

Can we multiply these matrices? The answer is yes! This is because the number of columns of the first matrix (3) is equal to the number of rows of the second matrix (3).

Now, what do you think the dimensions of the product matrix, say matrix C, should be? Well, if you answered 2 x 4, you are right!

However, if matrix A had the dimensions 2 x 3 and matrix B had the dimensions 2 x 2, multiplying them wouldn't be possible. Each row of A has 3 numbers, but each column of B has only 2, so there is nothing to pair the third number with.

One more rule surprises many students: the order matters. A x B and B x A are usually not the same, and sometimes only one of them is even possible. With A as 2 x 3 and B as 3 x 4, A x B works, but B x A does not (4 columns vs. 2 rows).

Mathematical Logic Behind Matrix Multiplication

Remember that each cell of the product is a dot product? The image given below shows the steps for calculating the product of two matrices.

Steps for calculating the dot product for matrix multiplication

  • Go row-by-column: take a row of matrix A and a column of matrix B.
  • Multiply the matching elements and add the results together.
  • Put the result in the cell where that row and that column meet. Refer to the image below to see where each element goes in the resulting matrix.

Example of placing each dot product in the result matrix

Let us also do one full example by hand, because we will check it against the Java program next. Take A = [[1, 2, 3], [4, 5, 6]] (2 x 3) and B = [[7, 8], [9, 10], [11, 12]] (3 x 2). The result is 2 x 2:

  • C[0][0] = row 0 of A with column 0 of B = 1x7 + 2x9 + 3x11 = 7 + 18 + 33 = 58
  • C[0][1] = row 0 of A with column 1 of B = 1x8 + 2x10 + 3x12 = 8 + 20 + 36 = 64
  • C[1][0] = row 1 of A with column 0 of B = 4x7 + 5x9 + 6x11 = 28 + 45 + 66 = 139
  • C[1][1] = row 1 of A with column 1 of B = 4x8 + 5x10 + 6x12 = 32 + 50 + 72 = 154

In Java, we do exactly this with the help of nested loops. In the section below, we will write a program for multiplying matrices in Java.

Step-By-Step Matrix Multiplication In Java (With User Input)

Now that we understand the rules and the process for multiplying matrices, let us implement them in a Java program. In this example, we will ask the user for the details of the matrices that we need to multiply.

Code Example:

import java.util.Scanner;

public class MatrixMultiplication {
    public static void main(String[] args) {
        // Create a scanner object to get user inputs
        Scanner scanner = new Scanner(System.in);

        // Input dimensions for Matrix A
        System.out.println("Enter the details for Matrix A");
        System.out.print("Enter number of rows for Matrix A: ");
        int rowsA = scanner.nextInt();
        System.out.print("Enter number of columns for Matrix A: ");
        int colsA = scanner.nextInt();

        // Input dimensions for Matrix B
        System.out.println("Enter the details for Matrix B");
        System.out.print("Enter number of rows for Matrix B: ");
        int rowsB = scanner.nextInt();
        System.out.print("Enter number of columns for Matrix B: ");
        int colsB = scanner.nextInt();

        // Check if matrices can be multiplied
        if (colsA != rowsB) {
            System.out.println("Matrix multiplication not possible. The number of columns of Matrix A must equal the number of rows of Matrix B.");
            return;
        }

        // Input values for Matrix A
        int[][] matrixA = new int[rowsA][colsA];
        System.out.println("Enter elements of Matrix A:");
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsA; j++) {
                matrixA[i][j] = scanner.nextInt();
            }
        }

        // Input values for Matrix B
        int[][] matrixB = new int[rowsB][colsB];
        System.out.println("Enter elements of Matrix B:");
        for (int i = 0; i < rowsB; i++) {
            for (int j = 0; j < colsB; j++) {
                matrixB[i][j] = scanner.nextInt();
            }
        }

        // Multiplying matrices: each cell is the dot product of a row of A and a column of B
        int[][] result = 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++) {
                    result[i][j] += matrixA[i][k] * matrixB[k][j];
                }
            }
        }

        // Print the product matrix
        System.out.println("Product Matrix:");
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                System.out.print(result[i][j] + "\t");
            }
            System.out.println();
        }

        scanner.close();
    }
}

Explanation Of The Code:

  • In the above code, we first take the dimensions of matrix A and matrix B from the user.
  • After we have the dimensions, we check whether the matrices meet the condition for multiplication. This step is important to prevent errors, like an ArrayIndexOutOfBoundsException later in the loops.
  • Once the sizes are valid, we read the elements of the matrices using nested for loops. These loops store the values in 2D arrays.
  • Next, using the formula result[i][j] += matrixA[i][k] * matrixB[k][j]; we calculate the dot product for every cell.
  • The variable k walks through the common dimension: the columns of A and the rows of B.
  • After the calculation, the product matrix is printed.

Output (matrices can be multiplied):

Enter the details for Matrix A
Enter number of rows for Matrix A: 2
Enter number of columns for Matrix A: 3
Enter the details for Matrix B
Enter number of rows for Matrix B: 3
Enter number of columns for Matrix B: 2
Enter elements of Matrix A:
1 2 3
4 5 6
Enter elements of Matrix B:
7 8
9 10
11 12
Product Matrix:
58    64
139    154

The program gives 58, 64, 139, and 154, exactly what we calculated by hand above.

Output (matrices can't be multiplied):

Enter the details for Matrix A
Enter number of rows for Matrix A: 2
Enter number of columns for Matrix A: 3
Enter the details for Matrix B
Enter number of rows for Matrix B: 2
Enter number of columns for Matrix B: 2
Matrix multiplication not possible. The number of columns of Matrix A must equal the number of rows of Matrix B.

Here, matrix A is 2 x 3 and matrix B is 2 x 2. Since 3 is not equal to 2, the program stops before asking for any elements.

Matrix multiplication flowchart

Instructors often add a twist to this assignment, like reading the matrices from a file or splitting the work into methods. If yours does, our Java homework help team can walk you through that version.

Java Program To Multiply Two Matrices

Now, let's build a Java program to multiply two fixed matrices, step by step. This version doesn't take input, which makes it easier to focus on the logic.

Step 1: Define Matrices A And B

First, we need to define the two matrices, A and B, that we want to multiply. We'll use two-dimensional arrays to represent them.

int[][] matrixA = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrixB = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};

In this example, we've defined two 3 x 3 matrices, matrixA and matrixB. You can replace these values with your own matrices of the size you need.

Step 2: Create A Result Matrix

Next, we'll create an empty matrix to store the result of the multiplication. Its size is set by the number of rows in matrix A and the number of columns in matrix B.

int rowsA = matrixA.length;
int colsA = matrixA[0].length;
int colsB = matrixB[0].length;

int[][] resultMatrix = new int[rowsA][colsB];

In Java, a new int array is automatically filled with zeros, so every cell starts at 0, which is what we need before we start adding.

Step 3: Perform Matrix Multiplication

Now, we'll implement the matrix multiplication algorithm. We'll use nested loops to go through the rows of A and the columns of B and compute each element of the result.

for (int i = 0; i < rowsA; i++) {
    for (int j = 0; j < colsB; j++) {
        for (int k = 0; k < colsA; k++) {
            resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j];
        }
    }
}

In the innermost loop, we calculate the sum of products for each element of the result matrix.

Step 4: Display The Result

Finally, let's display the result matrix.

System.out.println("Result Matrix (C):");
for (int i = 0; i < rowsA; i++) {
    for (int j = 0; j < colsB; j++) {
        System.out.print(resultMatrix[i][j] + " ");
    }
    System.out.println(); // Move to the next row
}

Now, let's put all the code together and run the program to see the output.

Code To Multiply Two Matrices:

public class MatrixMultiplication {
    public static void main(String[] args) {
        int[][] matrixA = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] matrixB = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};

        int rowsA = matrixA.length;
        int colsA = matrixA[0].length;
        int colsB = matrixB[0].length;

        int[][] resultMatrix = 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++) {
                    resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j];
                }
            }
        }

        System.out.println("Result Matrix (C):");
        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                System.out.print(resultMatrix[i][j] + " ");
            }
            System.out.println(); // Move to the next row
        }
    }
}

Output:

Result Matrix (C):
30 24 18
84 69 54
138 114 90

The output is the result matrix C, obtained by multiplying the two input matrices, A and B. Each number in it is the dot product of one row of A and one column of B. For example, the first cell is 1x9 + 2x6 + 3x3 = 30.

A Reusable multiply() Method With Proper Checks

Many instructors want the multiplication in its own method that returns the result, instead of doing everything inside main(). Here is a version that also checks for empty and jagged arrays, which neither program above does:

import java.util.Arrays;

public class Main {
    // Returns A x B, or throws an exception if the sizes don't fit
    static int[][] multiply(int[][] A, int[][] B) {
        if (A.length == 0 || B.length == 0)
            throw new IllegalArgumentException("Matrices must not be empty");
        int n = A[0].length;
        for (int[] row : A)
            if (row.length != n) throw new IllegalArgumentException("Matrix A is not rectangular");
        for (int[] row : B)
            if (row.length != B[0].length) throw new IllegalArgumentException("Matrix B is not rectangular");
        if (n != B.length)
            throw new IllegalArgumentException("Cannot multiply " + A.length + "x" + n
                    + " by " + B.length + "x" + B[0].length);

        int[][] C = new int[A.length][B[0].length];
        for (int i = 0; i < A.length; i++)
            for (int j = 0; j < B[0].length; 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 x 3
        int[][] B = {{7, 8}, {9, 10}, {11, 12}};     // 3 x 2

        System.out.println(Arrays.deepToString(multiply(A, B)));   // 2 x 2
        System.out.println(Arrays.deepToString(multiply(B, A)));   // 3 x 3: Order Matters!

        try {
            multiply(A, A);                                        // 2x3 times 2x3
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

[[58, 64], [139, 154]]
[[39, 54, 69], [49, 68, 87], [59, 82, 105]]
Error: Cannot multiply 2x3 by 2x3

A few things to notice here:

  • multiply(A, B) gives a 2 x 2 matrix, while multiply(B, A) gives a completely different 3 x 3 matrix. This shows the "order matters" rule in action.
  • Instead of printing an error and returning, the method throws an IllegalArgumentException, so the code that called it decides what to do.
  • Arrays.deepToString() prints a 2D array in one line, which is handy for testing. If you want more ways to display arrays, see our guide on how to print an array in Java.

Making It Faster: Loop Order And Parallel Rows

The triple loop does about n x n x n multiplications, so the time grows very quickly with the size. Its time complexity is O(n³) for two n x n matrices. For small homework matrices, this doesn't matter. For large ones, two simple changes make a big difference.

We timed three versions on two 800 x 800 matrices, keeping the best of five runs each:

import java.util.Random;
import java.util.stream.IntStream;

public class Main {
    static final int N = 800;

    static long[][] ijk(int[][] A, int[][] B) {
        long[][] C = new long[N][N];
        for (int i = 0; i < N; i++)
            for (int j = 0; j < N; j++)
                for (int k = 0; k < N; k++)
                    C[i][j] += (long) A[i][k] * B[k][j];
        return C;
    }

    static long[][] ikj(int[][] A, int[][] B) {
        long[][] C = new long[N][N];
        for (int i = 0; i < N; i++)
            for (int k = 0; k < N; k++) {
                long a = A[i][k];
                for (int j = 0; j < N; j++)
                    C[i][j] += a * B[k][j];      // Walks Along A Row Of B
            }
        return C;
    }

    static long[][] parallelIkj(int[][] A, int[][] B) {
        long[][] C = new long[N][N];
        IntStream.range(0, N).parallel().forEach(i -> {
            for (int k = 0; k < N; k++) {
                long a = A[i][k];
                for (int j = 0; j < N; j++)
                    C[i][j] += a * B[k][j];
            }
        });
        return C;
    }

    interface M { long[][] run(int[][] A, int[][] B); }

    static double time(M m, int[][] A, int[][] B) {
        double best = Double.MAX_VALUE;
        for (int r = 0; r < 5; r++) {               // Repeat And Keep The Best Run
            long t = System.nanoTime();
            m.run(A, B);
            best = Math.min(best, (System.nanoTime() - t) / 1e6);
        }
        return best;
    }

    public static void main(String[] args) {
        Random rnd = new Random(42);
        int[][] A = new int[N][N], B = new int[N][N];
        for (int i = 0; i < N; i++)
            for (int j = 0; j < N; j++) { A[i][j] = rnd.nextInt(100); B[i][j] = rnd.nextInt(100); }

        boolean same = java.util.Arrays.deepEquals(ijk(A, B), ikj(A, B))
                    && java.util.Arrays.deepEquals(ijk(A, B), parallelIkj(A, B));
        System.out.println("All three give the same result: " + same);
        System.out.println("Java " + System.getProperty("java.version") + ", " + N + "x" + N
                + " matrices, " + Runtime.getRuntime().availableProcessors() + " CPU cores");
        System.out.printf("i-j-k loop order:      %6.0f ms%n", time(Main::ijk, A, B));
        System.out.printf("i-k-j loop order:      %6.0f ms%n", time(Main::ikj, A, B));
        System.out.printf("i-k-j + parallel rows: %6.0f ms%n", time(Main::parallelIkj, A, B));
    }
}

Output:

All three give the same result: true
Java 21.0.10, 800x800 matrices, 2 CPU cores
i-j-k loop order:        1203 ms
i-k-j loop order:         200 ms
i-k-j + parallel rows:    101 ms

All three versions gave identical results, but the times were very different:

  • Swapping the j and k loops (i-k-j order) made it about 6 times faster. Java stores a 2D array as an array of rows. In the i-j-k order, the inner loop jumps down a column of B (B[k][j] with k changing), touching a different row in memory every step. In the i-k-j order, the inner loop walks along a single row of B, which the CPU's cache handles much better. The math is exactly the same.
  • Running the rows in parallel then cut that time in half on our 2-core machine. Every row of the result is independent, so different CPU cores can calculate different rows at the same time. On a computer with more cores, the gain is usually bigger.
  • We also used long for the result here, because the sum of 800 products can get larger than an int can safely hold. More on that in the mistakes section.

Your timings will differ, but i-k-j should still beat i-j-k by a wide margin.

How To Do Concurrent Matrix Multiplication In Java?

Modern computers have several CPU cores. We can use multithreading to speed up matrix multiplication by breaking it into smaller tasks that run in parallel. A common way to do this is Java's Fork/Join framework. Here is a common version of this program, and it is worth looking at closely, because it has a hidden problem:

import java.util.concurrent.*;

// Extending The RecursiveAction To Use The Fork/Join Framework
public class Main extends RecursiveAction
{
    private int[][] A, B, C; // The Matrices
    private int row;

    // Constructor For Initializing The Data
    public Main(int[][] A, int[][] B, int[][] C, int row)
    {
        this.A = A;
        this.B = B;
        this.C = C;
        this.row = row;
    }

    @Override
    protected void compute()
    {
        if (row >= A.length)
            return;

        // Multiplication Process For One Row
        for (int j = 0; j < B[0].length; j++)
            for (int k = 0; k < A[0].length; k++)
                C[row][j] += A[row][k] * B[k][j];

        // Creating The Next Task To Process
        invokeAll(new Main(A, B, C, row + 1));
    }

    public static void main(String[] args)
    {
        int[][] A = {{10, 21}, {30, 43}};
        int[][] B = {{50, 65}, {70, 87}};
        int[][] C = new int[2][2];

        // Creating A ForkJoinPool To Execute The Tasks
        ForkJoinPool pool = new ForkJoinPool();

        // The Execution Will Start
        pool.invoke(new Main(A, B, C, 0));

        System.out.println("Concurrent Matrix Multiplication: ");
        for (int[] row : C)
            for (int num : row)
                System.out.print(num + " ");

        System.out.println();
    }
}

Output:

Concurrent Matrix Multiplication:
1970 2477 4510 5691

Explanation Of The Code:

  • At first, the Main class extends RecursiveAction to use the Fork/Join framework.
  • Next, the constructor stores the matrices and the row number that this task should handle.
  • Then, the compute() method, marked with @Override, multiplies one row.
  • After that, it creates a task for the next row and calls invokeAll() on it.
  • At last, main() creates the input matrices and starts the first task with ForkJoinPool.invoke().

The answer is correct, but the program is not actually concurrent. Each task finishes its own row and only then creates the task for the next row, so the rows are still calculated one after another, just with extra overhead. It also nests one call per row, so a matrix with thousands of rows can crash with a StackOverflowError. For real parallel work, all the row tasks must be started together. The simplest way to do that in modern Java is a parallel stream:

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        int[][] A = {{10, 21}, {30, 43}};
        int[][] B = {{50, 65}, {70, 87}};
        int[][] C = new int[A.length][B[0].length];

        // Every Row Of C Is Independent, So Rows Can Be Computed At The Same Time
        IntStream.range(0, A.length).parallel().forEach(i -> {
            for (int j = 0; j < B[0].length; j++)
                for (int k = 0; k < B.length; k++)
                    C[i][j] += A[i][k] * B[k][j];
        });

        System.out.println("Parallel Matrix Multiplication: ");
        for (int[] row : C)
            for (int num : row)
                System.out.print(num + " ");
        System.out.println();
    }
}

Output:

Parallel Matrix Multiplication:
1970 2477 4510 5691

IntStream.range(0, A.length).parallel() hands the row numbers out to all available cores at once. It is safe here because each row writes only to its own row of C, so no two threads ever touch the same cell. This is the same idea that gave us the 2x speedup in the timing test above.

How To Transpose And Multiply A Matrix In Java?

Sometimes, instead of multiplying two different matrices, you have to multiply a matrix by its own transpose. This is very common in machine learning, statistics, and other calculations.

Let us check the following code, where we first transpose a matrix and then multiply.

public class Main
{
    public static int[][] trans(int[][] M) // Function To Transpose
    {
        int rows = M.length; // Getting The Number Of Rows
        int cols = M[0].length; // Getting The Number Of Columns
        int[][] T = new int[cols][rows];

        // Calculating The Transpose
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++)
                T[j][i] = M[i][j];

        return T;
    }

    public static int[][] multiply(int[][] A, int[][] B) // Function To Multiply
    {
        int[][] C = new int[A.length][B[0].length];

        // Implementing The Multiply Logic
        for (int i = 0; i < A.length; i++)
            for (int j = 0; j < B[0].length; j++)
                for (int k = 0; k < A[0].length; k++)
                    C[i][j] += A[i][k] * B[k][j];
        return C;
    }

    public static void main(String[] args)
    {
        int[][] A = {{12, 21}, {34, 40}};
        int[][] T = trans(A);
        int[][] result = multiply(A, T);

        System.out.println("Transpose And Multiply Matrix: ");
        for (int[] row : result)
            for (int num : row)
                System.out.print(num + " ");

        System.out.println();
    }
}

Explanation Of The Code:

  • At first, a matrix is created and passed to the trans() function.
  • In that function, we swap rows with columns (T[j][i] = M[i][j]) to get the transpose matrix.
  • Then, the multiply() function is called, and the matrix and its transpose are multiplied using the same logic as before.
  • In the end, we print the result on the screen.

Output:

Transpose And Multiply Matrix:
585 1248 1248 2756

The result is the 2 x 2 matrix [[585, 1248], [1248, 2756]]. Notice that it is symmetric: the top-right and bottom-left numbers are the same. A matrix multiplied by its own transpose is always symmetric, which is a quick way to check your code.

Comparison Table Between Strassen Vs. Naive Matrix Multiplication In Java

Along with the naive (triple loop) approach, there is a more advanced method known as the Strassen algorithm, which has a lower time complexity.

Here is a comparison table between the Strassen and naive multiplication approaches.

CriteriaNaive Matrix MultiplicationStrassen Matrix Multiplication
Time ComplexityO(n³)About O(n^2.81)
ImplementationSimpleComplex (recursive, splits matrices into quarters)
Speed In PracticeFaster for small and medium matricesOnly faster for very large matrices
Memory UsageLowHigher (needs extra temporary matrices)
Numerical StabilityStableLess stable with decimal (floating-point) numbers
Code LengthShortLong

For any class assignment, the naive method (preferably in i-k-j order) is the right choice unless the question specifically asks for Strassen.

Common Mistakes To Avoid While Multiplying Matrices In Java

Let us now look at some common mistakes that beginners make while multiplying matrices in Java, and how to avoid them in your code.

Common mistakes to avoid while multiplying matrices in Java

1) Incorrect Matrix Size Assumptions

Many times, programmers take user input and directly apply the formula. Since this causes errors, we should always validate the dimensions of the matrices before multiplying. Always remember the rule: the number of columns of the first matrix must be the same as the number of rows of the second one.

2) Misplaced Loop Indices

Another mistake is in the indexes inside the nested loop. Notice how we have a third variable, k, in the loop. It walks through the common dimension of the two matrices. The formula is always A[i][k] * B[k][j]: k is the column in A and the row in B. Writing B[j][k] by mistake still compiles, but gives wrong numbers (or an exception if B isn't square).

3) Using = Instead Of +=

No error, no warning, just wrong numbers:

public class Main {
    public static void main(String[] args) {
        int[][] A = {{1, 2}, {3, 4}};
        int[][] B = {{5, 6}, {7, 8}};
        int[][] wrong = new int[2][2], right = new int[2][2];

        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 2; j++)
                for (int k = 0; k < 2; k++) {
                    wrong[i][j] = A[i][k] * B[k][j];   // = Keeps Only The Last Product
                    right[i][j] += A[i][k] * B[k][j];  // += Adds Them All Up
                }

        System.out.println("With = : " + java.util.Arrays.deepToString(wrong));
        System.out.println("With +=: " + java.util.Arrays.deepToString(right));
    }
}

Output:

With = : [[14, 16], [28, 32]]
With +=: [[19, 22], [43, 50]]

With =, each cell keeps only the last product (k = 1), instead of adding all the products together.

4) Reusing The Output Matrix Without Resetting It

Java fills a new int array with zeros, so you don't need to set the starting values yourself. The problem comes when you reuse the same result array for a second multiplication:

public class Main {
    public static void main(String[] args) {
        int[][] A = {{1, 2}, {3, 4}};
        int[][] C = new int[2][2];

        for (int round = 1; round <= 2; round++) {   // Multiplying A x A Twice
            for (int i = 0; i < 2; i++)
                for (int j = 0; j < 2; j++)
                    for (int k = 0; k < 2; k++)
                        C[i][j] += A[i][k] * A[k][j];
            System.out.println("Round " + round + ": " + java.util.Arrays.deepToString(C));
        }
    }
}

Output:

Round 1: [[7, 10], [15, 22]]
Round 2: [[14, 20], [30, 44]]

The second round should have printed the same answer, but it doubled, because the new products were added on top of the old ones. Create a fresh array with new int[rows][cols] for each multiplication.

5) Integer Overflow

An int in Java can only hold values up to about 2.1 billion. With bigger numbers, the sum quietly wraps around:

public class Main {
    public static void main(String[] args) {
        int[][] A = {{50000, 50000}};       // 1 x 2
        int[][] B = {{50000}, {50000}};     // 2 x 1

        int asInt = 0;
        long asLong = 0;
        for (int k = 0; k < 2; k++) {
            asInt += A[0][k] * B[k][0];             // int * int Overflows
            asLong += (long) A[0][k] * B[k][0];     // Cast First, Then Multiply
        }
        System.out.println("int result:  " + asInt);
        System.out.println("long result: " + asLong);
    }
}

Output:

int result:  705032704
long result: 5000000000

50,000 x 50,000 is 2.5 billion, which is already too big for an int. Use a long[][] result and cast before multiplying, like (long) A[i][k] * B[k][j], when your values can be large.

The Use Of Matrix Multiplication In Real-World Applications

As we said before, matrix multiplication is not only used in math class, but also across computer science. Let us see some of its use cases below:

  • Game Development And Graphics: The 3D characters and objects you see on your screen are defined by points called vertices, and these points are moved with matrices. Rotation, scaling, and translation are all done by multiplying a matrix with the vertices of an object. This is how a game decides how characters move from one position to another.
  • Artificial Intelligence & Machine Learning: Machine learning and deep learning use matrix multiplication at their core. In a neural network, forward propagation multiplies the input by a matrix of weights at each layer, and training (backpropagation) uses more matrix multiplication to adjust those weights.
  • Image Processing: Images are stored as matrices of pixel values. Effects like blurring, sharpening, and edge detection slide a small matrix, called a kernel or filter, across the image. This process is called convolution, and it is a close relative of matrix multiplication. This is how computer vision programs find edges and shapes.

If you want to keep practicing with problems like this, our list of Java coding challenges has more exercises that use 2D arrays and nested loops.

Conclusion

I hope you now have a clear picture of multiplying matrices in Java. At first glance, it may look like just a math exercise. However, as we discussed above, matrices are used across many tech industries.

Keep the rules in mind: check the sizes first, use += with the k loop, and watch for overflow. And if your matrices get large, remember that a simple loop-order change can make the same code several times faster.

Takeaways:

  • Each cell of the product matrix is the dot product of a row of the first matrix and a column of the second.
  • Always check that the number of columns of A equals the number of rows of B before multiplying.
  • The order matters: A x B and B x A are usually different.
  • Swapping the inner loops to i-k-j order is faster for large matrices, and rows can be computed in parallel.
  • Watch out for = instead of +=, reused result arrays, and integer overflow.

Frequently Asked Questions

What is the condition for multiplying two matrices in Java?

The number of columns in the first matrix must equal the number of rows in the second matrix. If A is m x n and B is n x p, the product is m x p. Check this in your code before running the loops.

What is the time complexity of matrix multiplication in Java?

The standard triple-loop method is O(n³) for two n x n matrices. In general, multiplying an m x n matrix by an n x p matrix takes O(m x n x p) operations. Strassen's algorithm lowers this to about O(n^2.81), but it is only faster for very large matrices.

Is A x B the same as B x A?

Usually not. Matrix multiplication is not commutative, so A x B and B x A can give different results, different sizes, or one of them may not be possible at all.

Why does my matrix multiplication give wrong numbers without any error?

The most common causes are using = instead of += in the inner loop, mixing up the indexes (B[j][k] instead of B[k][j]), reusing a result array that already has values, or integer overflow with large numbers. All four compile and run normally.

Can I multiply matrices of different sizes in Java?

Yes, as long as the inner dimensions match. For example, a 2 x 3 matrix can be multiplied by a 3 x 4 matrix, and the result will be 2 x 4. The matrices do not need to be square.

Should I use a library for matrix multiplication in Java?

For assignments, write the loops yourself, since that is usually what is being graded. For real projects with large matrices, libraries like EJML or Apache Commons Math are well tested and handle many more operations.