Skip to content
Home » Java Programs » Multiplication of Two Matrix in Java

Multiplication of Two Matrix in Java

Basic multiplication of two matrix in java. Multiply the components of the first row of the first matrix with the first column of the second matrix, then add the product of the elements. Repeat until each row of the first matrix has been multiplied by each column of the second matrix.

Multiply Two Matrices in Java

In mathematics, a product is a number that is obtained by multiplying two or more other numbers together. When you multiply 2 and 5, for example, you obtain a product of 10. Multiplication is a crucial aspect of math.

Decision-Making Statement in Java

Decision Making in Java facilitates the creation of decision-driven statements and the execution of a specific set of code in response to specified situations. If a condition is true, the if statement will execute a block of statements; if the condition is false, the if statement will not. 

In Java, the if statement is used to execute a block of code if a condition is true. If a condition evaluates to false, the if and else statement is used with an if statement to run code. The if else if statement is also used to test multiple conditions.

Row in Multiply Two Matrices in Java

A Row object has an array of current column values as well as an array of original column values, as well as methods for accessing and setting column values. It also records which columns have changed, as well as whether the change was a delete, insert, or update.

Column Definition

The matrix’s entries or elements are the numbers, symbols, or expressions that make up the matrix. Rows and columns are the horizontal and vertical lines of entries in a matrix, respectively. 

Multiplication of Two Matrix in Java

//multiplication of two matrix in java 
public class Main 
{ 
public static void main(String[] args)
{ 
int row1, col1, row2, col2; 
int a[][] = { 
{9, 7, 1}, 
{3, 1, 1}, 
{1, 2, 2} 
}; 
int b[][] = { 
{3, 5, 7}, 
{1, 0, 1}, 
{1, 3, 1} 
}; 
row1 = a.length; 
col1 = a[0].length; 
row2 = b.length; 
col2 = b[0].length; 
if(col1 != row2){ 
System.out.println("Matrices cannot be multiplied"); 
} 
else{ 
int prod[][] = new int[row1][col2]; 
for(int i = 0; i < row1; i++){ 
for(int j = 0; j < col2; j++){ 
for(int k = 0; k < row2; k++){ 
prod[i][j] = prod[i][j] + a[i][k] * b[k][j]; 
} 
} 
} 
System.out.println("Product of two matrices: "); 
for(int i = 0; i < row1; i++){ 
for(int j = 0; j < col2; j++){ 
System.out.print(prod[i][j] + " "); 
} 
System.out.println(); 
} 
} 
} 
} 

Output:

Product of two matrices:
35 48 71
11 18 23
7  11  11