Matrix Multiplication in Java using Scanner, Class, and Function [Example]

Hello guys, if you are looking for a matrix multiplication example in Java using the scanner for user input, and using class and object-oriented programming then you have come to the right place. In this Java tutorial, I will show you how to multiply matrix in Java using an array, scanner, and object-oriented programming. We will create a class to represent matrix and then define a multiplication method 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 the Fibonacci series, Prime Numbers, Factorial, and palindrome check, but what makes this program interesting is the use of the two-dimensional array to represent a matrix in Java. 

Since the matrix has both rows and columns, the 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 the 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 matrices with 2 here are 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.

And, if you want to revise your data structure and algorithms skills then I highly recommend you to join Data Structures and Algorithms: Deep Dive Using Java course by Tim Buchalaka and his team on Udemy. This is one of the better courses to learn essential data structure like an array, linked list, tree, etc in the Java programing language. 




Matrix Multiplication

In order to multiply two matrices, you need to calculate the dot product of 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 that 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 that 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.

Btw, if you struggle with Matrix multiplication or Linear Algebra in genera. I suggest you join the Become a Linear Algebra Master course on Udemy to quickly revise essential Linear Algebra concepts, which will help you in competitive programming and coding interviews. It also has a detailed chapter on Matrix multiplication. 

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

How to Multiply Two Matrices in Java



Matrix Multiplication in Java with Scanner and OOP

Here is our complete Java program to multiply one matrix with another in Java. In this program, we have a Matrix class that has rows and columns and holds the matrix numbers into a two-dimensional array. The Matrix class also has a 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 a 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 like 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 throws java.lang.IllegalArgumetnException.  You can further see the Clean Code book by Uncle Bob Martin 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("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[0].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. In this program, we have used Scanner to take user input to popular matrices for multiplication and we have also used Object oriented programming, classes, and methods to implement Matrix multiplication logic in Java. You can use this program for trying and testing. You should even try to write a 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 Learn Java Unit Testing with Junit & Mockito in the 30 Steps course on Udemy, a Unit testing, 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 the 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 a 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 a given String in Java? (solution)
  • How to check if the 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 the given Integer is Palindrome in Java? (solution)

Thanks for reading this tutorial so far. If you find this Matrix Multiplication Coding problem solution in Java useful then please share it with your friends and colleagues. If you have any questions or feedback then please ask in comments. 

P. S. -  If you are new to Java Programming and looking for a free online course to learn Java Programming essentials then I highly recommend you joining the  Java Tutorial for Complete Beginners (FREE) course on Udemy. More than 1.2 million students have already joined this courses to learn Java online. 

3 comments:

  1. the product should be:
    5 6
    11 14

    ReplyDelete
  2. 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++) {
    product[i][j] += data[i][k] * other.data[k][j];
    }
    // product[i][j] = sum;
    }
    }
    return new Matrix(product);
    }

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.