LearnFrenzy
Sign in Take a free test

Arrays in Java · Java Array Programs · Question 5

Matrix multiplication with 2D arrays in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Multiply two matrices using 2D arrays (checking that the dimensions are compatible) and print the result row by row.

Solution
Main.java
import java.util.Arrays;

public class Main {
    static int[][] multiply(int[][] a, int[][] b) {
        if (a[0].length != b.length) throw new IllegalArgumentException("incompatible sizes");
        int n = a.length, m = b[0].length, k = b.length;
        int[][] c = new int[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                for (int x = 0; x < k; x++) c[i][j] += a[i][x] * b[x][j];
        return c;
    }

    public static void main(String[] args) {
        int[][] a = {{1, 2, 3}, {4, 5, 6}};
        int[][] b = {{7, 8}, {9, 10}, {11, 12}};
        for (int[] row : multiply(a, b)) System.out.println(Arrays.toString(row));
        try { multiply(a, a); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
    }
}

Output Verified by compiling and running

[58, 64]
[139, 154]
incompatible sizes

Each result cell is the dot product of a row of a and a column of b; the inner dimension must match.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links