# How to Multiply Two Matrices in Java

I first learned about matrix in class 12th and I first wrote the program to multiply two matrices on my first semester of engineering, so, when I thought about this program, It brings a lot of memories from the past. It's actually a beginner exercise to develop coding logic, much like Fibonacci, prime, and palindrome check, but what make this program interesting is the use of the two-dimensional array to represent a matrix in Java.  Since matrix has both rows and columns, two-dimensional array just naturally fits into the requirement. Another important thing to solve this problem is to remember the rule of matrix multiplication in mathematics. If you don't remember the rule, just forget about how to solve this problem, unless you have access to Google. So, first, we'll refresh the rules of multiplication and then we'll look into coding aspect.

A Matrix is nothing but a two-dimensional array of numbers. It has rows and columns, for example following matrix has 2 rows and 3 columns
[2, 4, 6]
[1, 3, 5]

To multiply a matrix by a single number is easy, just multiply each element of a matrix with that number is known a scalar multiplication.

For example, if you multiple above matrix with 2 here is how the matrix multiplication will work

Matrix Multiply Constant

These are the calculations:
2×2=8 2×4=8 2x6=12
2×1=2 2×3=6 2x5=10

We call the number ("2" in this case) a scalar, so this is called "scalar multiplication", but that's not what you will learn here. In this program, you will learn about how to multiply one matrix to another using array in Java.

## Multiplying one matrix to another matrix

In order to multiply two matrices, you need to calculate the dot product or rows and columns. The "Dot Product" is where we multiply matching members, then sum up:

(1, 2, 3) • (7, 9, 11) = 1×7 + 2×9 + 3×11 = 58

We match the 1st members (1 and 7), multiply them, likewise for the 2nd members (2 and 9) and the 3rd members (3 and 11), and finally sum them up.

There are also two rules of matrix multiplication which you need to remember:
• The number of columns of the first matrix must be equal to the number of rows of the second matrix. For example, if the first matrix has 2 columns then you can multiply it with another matrix which has 2 rows.
• The product matrix will have the same number of rows as the first matrix, and the same number of columns as the second matrix.

Here is a nice diagram which explains matrix multiplication beautifully with an example:

## Java Program to multiply two matrices in Java

Here is our complete Java program to multiply one matrix with another in Java. In this program, we have a Matrix class which has rows and columns and holds the matrix numbers into a two-dimensional array. The Matrix class also have read() method to read user input using Scanner and populate the matrix. It also has a multiply(Matrix other) method to perform the multiplication of this matrix with given matrix and returns a new Matrix whose values are equal to the product of two matrices.  It also has a print method to nicely print the matrix into the command prompt.

The multiply(Matrix other) method also does some pre-validation as per the rules of matrix multiplication e.g. it checks if rows of given Matrix is equal to the column of this matrix or not, if they are not equal then matrix multiplication cannot be performed, hence it throw java.lang.IllegalArgumetnException.  See Clean Code to learn more about pre-validation in methods.

```import java.util.Scanner;

/*
* Java Program to multiply two matrices
*/
public class MatricsMultiplicationProgram {

public static void main(String[] args) {

System.out
.println("Welcome to Java program to calcualte multiplicate of two matrices");
Scanner scnr = new Scanner(System.in);

System.out.println("Please enter details of first matrix");
System.out.print("Please Enter number of rows: ");
int row1 = scnr.nextInt();
System.out.print("Please Enter number of columns: ");
int column1 = scnr.nextInt();
System.out.println();
System.out.println("Enter first matrix elements");
Matrix first = new Matrix(row1, column1);
first.read();

System.out.println("Please enter details of second matrix");
System.out.print("Please Enter number of rows: ");
int row2 = scnr.nextInt();
System.out.print("Please Enter number of columns: ");
int column2 = scnr.nextInt();
System.out.println();
System.out.println("Enter second matrix elements");

Matrix second = new Matrix(row2, column2);
second.read();

Matrix product = first.multiply(second);

System.out.println("first matrix: ");
first.print();
System.out.println("second matrix: ");
second.print();
System.out.println("product of two matrices is:");
product.print();

scnr.close();

}

}

/*
* Java class to represent a Matrix. It uses a two dimensional array to
* represent a Matrix.
*/
class Matrix {
private int rows;
private int columns;
private int[][] data;

public Matrix(int row, int column) {
this.rows = row;
this.columns = column;
data = new int[rows][columns];
}

public Matrix(int[][] data) {
this.data = data;
this.rows = data.length;
this.columns = data.length;
}

public int getRows() {
return rows;
}

public int getColumns() {
return columns;
}

/**
* fills matrix from data entered by user in console
*
* @param rows
* @param columns
*/
public void read() {
Scanner s = new Scanner(System.in);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
data[i][j] = s.nextInt();
}
}

}

/**
*
* @param a
* @param b
* @return
*/
public Matrix multiply(Matrix other) {
if (this.columns != other.rows) {
throw new IllegalArgumentException(
"column of this matrix is not equal to row "
+ "of second matrix, cannot multiply");
}

int[][] product = new int[this.rows][other.columns];
int sum = 0;
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < other.columns; j++) {
for (int k = 0; k < other.rows; k++) {
sum = sum + data[i][k] * other.data[k][j];
}
product[i][j] = sum;
}
}
return new Matrix(product);
}

/**
*
* @param matrix
*/
public void print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}

}

Output:
Welcome to Java program to calculate multiplicate of two matrices
Please enter details of the first matrix
Please Enter number of rows: 2
Please Enter number of columns: 2

Enter first matrix elements
1
2
3
4
Please enter details of the second matrix
Please Enter number of rows: 2
Please Enter number of columns: 2

Enter second matrix elements
1
2
2
2
first matrix:
1 2
3 4
second matrix:
1 2
2 2
product of two matrices is:
5 11
22 36 ```

That's all about how to write a Java program to multiply two matrices. You can use this program for trying and testing. You should even try to write JUnit test for this program to check various boundary conditions. If you don't know how to write Junit test cases in Java then please refer to JUnit in Action or Test Driven, a TDD and acceptance TDD guide for Java developers. These exercises will help you to build your programming logic and also help you to understand when and how to use data structure while solving problems.

Other Java Programming exercises for beginners
• How to implement binary search using recursion in Java? (solution)
• How to calculate the average of all numbers of an array in Java? (program)
• How to implement Linear Search in Java? (solution)
• How to calculate the square root of a given number in Java? (solution)
• How to calculate Area of Triangle in Java? (program)
• How to find all permutations of a given String in Java? (solution)
• How to remove duplicate elements from the array in Java? (solution)
• How to check if two given Strings are Anagram in Java? (solution)
• How to print Fibonacci series in Java (solution)
• How to check if a year is a leap year in Java? (solution)
• How to reverse a String in place in Java? (solution)
• How to check if given number is prime in Java (solution)
• How to find the highest occurring word from a given file in Java? (solution)
• How to count vowels and consonants in given String in Java? (solution)
• How to check if given String is palindrome or not in Java? (solution)
• How to remove duplicate characters from String in Java? (solution)
• How to check if a String contains duplicate characters in Java? (solution)
• How to reverse words in a given String in Java? (solution)
• How to calculate the sum of all elements of an array in Java? (program)
• How to check if two rectangles intersect with each other in Java? (solution)
• How to reverse an array in place in Java? (solution)
• How to find if given Integer is Palindrome in Java? (solution)

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass

#### 1 comment:

1. the product should be:
5 6
11 14