Java Program to find Matrix Multiplication

You are Here:

Find Matrix Multiplication

In the following example, we will multiply the two given matrices (two-dimensional arrays).

Example

Java Compiler
public class myClass { public static void main(String[] args) { int i, j, k; int[][] arr1 = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1} }; int[][] arr2 = { {2, 2, 2}, {2, 2, 2}, {2, 2, 2} }; int[][] arr3 = new int[3][3]; System.out.println("Matrix A (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) System.out.format("%d ", arr1[i][j]); System.out.println(); } System.out.println("\nMatrix B (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) System.out.format("%d ", arr2[i][j]); System.out.println(""); } for(i=0; i<3; i++) { for(j=0; j<3; j++) { for(k=0; k<3; k++) arr3[i][j] = arr3[i][j] + arr1[i][k] * arr2[k][j]; } } System.out.println("\nMatrix Multiplication (A x B):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) System.out.format("%d ", arr3[i][j]); System.out.println(); } } }

Output

Matrix A (3 x 3): 1 1 1 1 1 1 1 1 1 Matrix B (3 x 3): 2 2 2 2 2 2 2 2 2 Matrix Multiplication (A x B): 6 6 6 6 6 6 6 6 6

In the following example, we will get the values for (3 x 3) Matrices A and B from the user and display the matrix multiplication.

Example

Java Compiler
import java.util.Scanner; public class myClass { public static void main(String[] args) { int i, j, k; int[][] arr1 = new int[3][3]; int[][] arr2 = new int[3][3]; int[][] arr3 = new int[3][3]; Scanner reader = new Scanner(System.in); System.out.println("Enter Matrix A (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) arr1[i][j] = reader.nextInt(); } System.out.println("\nEnter Matrix B (3 x 3):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) arr2[i][j] = reader.nextInt(); } for(i=0; i<3; i++) { for(j=0; j<3; j++) { for(k=0; k<3; k++) arr3[i][j] = arr3[i][j] + arr1[i][k] * arr2[k][j]; } } System.out.println("\nMatrix Multiplication (A x B):"); for(i=0; i<3; i++) { for(j=0; j<3; j++) System.out.format("%d ", arr3[i][j]); System.out.println(); } } }

Output

Enter Matrix A (3 x 3): 2 2 2 2 2 2 2 2 2 Enter Matrix B (3 x 3): 4 4 4 4 4 4 4 4 4 Matrix Multiplication (A x B): 24 24 24 24 24 24 24 24 24

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.

We are working to cover every Single Concept in Java.