Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 55

Matrix Multiplication in Java

In this lesson: Matrix multiplication program in Java using 2D arrays — logic, dry run and output. Copy & run now. In Hindi & English.

What is matrix multiplication

Matrix multiplication combines two matrices (2D arrays) into a new one. Each result cell is built by taking a row from the first matrix, a column from the second, multiplying matching elements, and adding them up. It is a classic exercise in nested loops and 2D arrays.

💡 Each result cell = (a row of A) · (a column of B): multiply matching elements and sum them.

The multiplication rule

For 2×2 matrices A and B, the top-left result cell is: (A's first row) times (B's first column):

c[0][0] = a[0][0]*b[0][0] + a[0][1]*b[1][0]

You repeat this pattern for every result cell, each pairing one row of A with one column of B.

The Java program

public class MatrixMul {
    public static void main(String[] args) {
        int[][] a = {{1, 2}, {3, 4}};
        int[][] b = {{5, 6}, {7, 8}};
        int[][] c = new int[2][2];

        for (int i = 0; i < 2; i++) {          // each row of A
            for (int j = 0; j < 2; j++) {      // each col of B
                for (int k = 0; k < 2; k++) {  // sum the products
                    c[i][j] += a[i][k] * b[k][j];
                }
            }
        }
        for (int[] row : c) {
            for (int x : row) System.out.print(x + " ");
            System.out.println();
        }
    }
}
19 22
43 50

Three loops: i and j pick the result cell, and k adds up the products of A's row and B's column for that cell.

Dry run

Dry Run — 2x2 matrix multiply, each cell's calculation
Result cellRow × ColumnCalculationValue
c[0][0]A row0 · B col01*5 + 2*7 = 5+1419
c[0][1]A row0 · B col11*6 + 2*8 = 6+1622
c[1][0]A row1 · B col03*5 + 4*7 = 15+2843
c[1][1]A row1 · B col13*6 + 4*8 = 18+3250
💡 Understand it this way

For each result cell, pair a row of A with a column of B, multiply matching elements, and add. c[0][0] uses A's first row and B's first column: 1*5 + 2*7 = 19.

When it is valid

Two matrices can be multiplied only if the columns of the first equal the rows of the second. An m×n matrix times an n×p matrix gives an m×p result. If the inner dimensions do not match, multiplication is not defined.

Common mistakes

  • Not initialising the result. Result cells must start at 0 before adding products (Java arrays do this by default).
  • Wrong index order. Use a[i][k] * b[k][j] — the shared index is k.
  • Mismatched dimensions. Columns of A must equal rows of B.
  • Expecting A×B = B×A. Matrix multiplication is not commutative.

Summary

  • Each result cell is a row of A dotted with a column of B.
  • Use three nested loops: two for the cell, one to sum products.
  • Valid only when A's columns equal B's rows.
  • An m×n times n×p matrix gives an m×p result.
  • Matrix multiplication is not commutative.

Next, practise 2D arrays in Java arrays, or nested loops in Floyd's triangle.

Frequently Asked Questions

How does matrix multiplication work?
Each cell of the result is the dot product of a row from the first matrix and a column from the second. You multiply matching elements and add them up. This needs three nested loops in code.
When can two matrices be multiplied?
Two matrices can be multiplied only when the number of columns in the first equals the number of rows in the second. The result has the rows of the first and the columns of the second.
Why does matrix multiplication need three loops?
Two loops pick each result cell (its row and column), and a third loop adds up the products of the row and column elements for that cell. So it is a loop inside a loop inside a loop.
Is matrix multiplication commutative?
No. Unlike numbers, A × B is usually not equal to B × A for matrices. The order matters, and sometimes only one order is even valid based on the dimensions.
How are matrices stored in Java?
As 2D arrays, like int[][] a. You access an element with two indexes, a[row][col], and loop over rows and columns to process the whole matrix.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicCalculator (Switch) Your progress: 55 / 61 (90%) · Lesson 56 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free