Matrix Multiplication Program in Java
Introduction
This program demonstrates how to multiply two matrices in Java. Matrix multiplication is a mathematical operation that produces a matrix from two matrices. For matrix multiplication to be possible, the number of columns in the first matrix must be equal to the number of rows in the second matrix.
Java Program
/**
* MatrixMultiplication class to demonstrate matrix multiplication in Java.
*/
public class MatrixMultiplication {
/**
* Multiplies two matrices and returns the result.
*
* @param matrix1 The first matrix.
* @param matrix2 The second matrix.
* @return The product of the two matrices.
*/
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {
int rows1 = matrix1.length;
int cols1 = matrix1[0].length;
int cols2 = matrix2[0].length;
// Resultant matrix of dimensions rows1 x cols2
int[][] result = new int[rows1][cols2];
// Multiply matrices
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}
/**
* Main method to test matrix multiplication.
*
* @param args Command line arguments.
*/
public static void main(String[] args) {
// Example matrices
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6}
};
int[][] matrix2 = {
{7, 8},
{9, 10},
{11, 12}
};
// Multiply the matrices
int[][] result = multiplyMatrices(matrix1, matrix2);
// Display the result
System.out.println("Product of the matrices:");
for (int[] row : result) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
Explanation
The program consists of a class MatrixMultiplication
with two methods:
multiplyMatrices
: This method takes two 2D arrays (matrices) as input and returns their product. It initializes a result matrix of appropriate dimensions and performs the matrix multiplication using nested loops.main
: This is the entry point of the program. It defines two example matrices, calls themultiplyMatrices
method to multiply them, and prints the resulting matrix.
Key Points:
- The dimensions of the result matrix are determined by the number of rows in the first matrix and the number of columns in the second matrix.
- The nested loops iterate through each element of the result matrix, computing the dot product of the corresponding row from the first matrix and the column from the second matrix.
- The program prints the resultant matrix in a readable format.