Java Online Compiler
Example: Matrix Multiplication in Java in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Matrix Multiplication in Java public class Main { // Method to multiply two matrices public static int[][] multiplyMatrices(int[][] matrixA, int[][] matrixB) { // Step 1: Get dimensions of the matrices int rowsA = matrixA.length; int colsA = matrixA[0].length; int rowsB = matrixB.length; int colsB = matrixB[0].length; // Step 2: Check for compatibility: colsA must be equal to rowsB if (colsA != rowsB) { System.out.println("Matrices dimensions are not compatible for multiplication."); return null; // Return null to indicate an error } // Step 3: Create a result matrix (rowsA x colsB) int[][] result = new int[rowsA][colsB]; // Step 4: Perform multiplication using three nested loops for (int i = 0; i < rowsA; i++) { // Iterate through rows of matrixA for (int j = 0; j < colsB; j++) { // Iterate through columns of matrixB for (int k = 0; k < colsA; k++) { // Iterate through columns of matrixA (or rows of matrixB) result[i][j] += matrixA[i][k] * matrixB[k][j]; } } } return result; } // Method to print a matrix public static void printMatrix(int[][] matrix) { if (matrix == null) { System.out.println("Cannot print null matrix."); return; } for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } public static void main(String[] args) { // Step 1: Define two matrices for multiplication int[][] matrixA = { {1, 2}, {3, 4} }; int[][] matrixB = { {5, 6}, {7, 8} }; System.out.println("Matrix A:"); printMatrix(matrixA); System.out.println("\nMatrix B:"); printMatrix(matrixB); // Step 2: Perform matrix multiplication int[][] productMatrix = multiplyMatrices(matrixA, matrixB); // Step 3: Print the result if (productMatrix != null) { System.out.println("\nProduct of Matrix A and Matrix B:"); printMatrix(productMatrix); } // Example with incompatible matrices System.out.println("\n--- Testing incompatible matrices ---"); int[][] matrixC = { {1, 2, 3}, {4, 5, 6} }; // 2x3 int[][] matrixD = { {7, 8}, {9, 10} }; // 2x2 System.out.println("Matrix C:"); printMatrix(matrixC); System.out.println("\nMatrix D:"); printMatrix(matrixD); System.out.println("\nAttempting to multiply Matrix C (2x3) and Matrix D (2x2):"); int[][] incompatibleProduct = multiplyMatrices(matrixC, matrixD); if (incompatibleProduct != null) { System.out.println("Product of Matrix C and Matrix D:"); printMatrix(incompatibleProduct); } } }
Output
Clear
ADVERTISEMENTS