Easy Array Problems Java

Matrix Multiplication in Java

Multiply two matrices and print the result matrix.

  • TimeO(r1 * c1 * c2), which is O(n^3) for two n x n matrices
  • SpaceO(r1 * c2) for the result
  • Hints3
  • Read3 min
Quick answer

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.

2D arraysNested loopsRow by column rule
1

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.

Input

Matrix A of size r1 x c1 and matrix B of size r2 x c2.

Output

The r1 x c2 product, one row per line.

Examples

Example 1
InputA = [[1, 2, 3], [4, 5, 6]], B = [[7, 8], [9, 10], [11, 12]]
Output58 64 139 154

The first value is 1*7 + 2*9 + 3*11 = 58.

Example 2
InputA = [[1, 2], [3, 4]], B = [[5, 6], [7, 8]]
Output19 22 43 50

The first value is 1*5 + 2*7 = 19.

Constraints

  • 1 <= rows, columns <= 200
  • c1 must equal r2
  • Every result fits in an int
2

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?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Each value of the answer is one row of A matched with one column of B.
2 Hint 2
Multiply the pairs in order and add them: a[i][0]*b[0][j] + a[i][1]*b[1][j] + ...
3 Hint 3
Use loop i for rows of A, j for columns of B, and k for the shared size.
4

Approach

Reveal the step-by-step approach
  1. Check that the columns of A equal the rows of B.
  2. Make a result array with rows of A and columns of B.
  3. For every row i of A and every column j of B, start sum at 0.
  4. Loop k over the shared size and add a[i][k] * b[k][j].
  5. Store sum in result[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.

5

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
6

Solution

Reveal the full Java solution
Solution.java
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 long for the sum if the numbers are large.
  • In this Scanner version you can swap the j and k loops 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.

TimeO(r1 * c1 * c2), which is O(n^3) for two n x n matrices
SpaceO(r1 * c2) for the result
7

Review 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

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us