Java Program to Check Two Matrices are Equal

Write a Java Program to Check Two Matrices are Equal or not. Or how to write a Java Program to find whether two multi-dimensional Matrixes are Equal or not with an example.

In this Java Matrix equal example, we declared two 2 * 2 integer matrices. Next, we used for loop to iterate the Matrix items. Within the for loop, we used the If statement to check whether each item in matrix x is not equal to matrix y item.

If True, we changed the isEqual value to 0 and applied the break statement to exit from the loop. Next, we used the isEqual variable in the If Else statement to print the output based on the isEqual value.

public class MatrixEqualOrNot {
	public static void main(String[] args) {
		int[][] x = {{1, 2}, {3, 4}};
		int[][] y = {{1, 2}, {3, 4}};
		
		int i, j, isEqual = 1;
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				if(x[i][j] != y[i][j]) {
					isEqual = 0;
					break;
				}
			}
		}
		if(isEqual == 1) {
			System.out.println("\nMatrix x is Equal to Matrix y");
		}
		else {
			System.out.println("\nMatrix x is Not Equal to Matrix y");
		}
	}
}

Java Matrix equal output

Matrix x is Equal to Matrix y

Java Program to Check Two Matrices are Equal example 2

This Java Matrix Equal code is the same as the above. However, this Java code for Multidimensional equal allows the user to enter the number of rows, columns, and the matrix items.

import java.util.Scanner;

public class MatrixEqualOrNot {
	private static Scanner sc;
	
	public static void main(String[] args) {
		int i, j, rows, columns, isEqual = 1;	
		
		sc= new Scanner(System.in);	
		
		System.out.println("\n Enter Matrix Rows & Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] x = new int[rows][columns];
		int[][] y = new int[rows][columns];
		
		System.out.println("\n Enter the First Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				x[i][j] = sc.nextInt();
			}		
		}
		
		System.out.println("\n Enter the Second Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				y[i][j] = sc.nextInt();
			}		
		}
		
		for(i = 0; i < x.length; i++)
		{
			for(j = 0; j < x[0].length; j++)
			{
				if(x[i][j] != y[i][j]) {
					isEqual = 0;
					break;
				}
			}
		}
		if(isEqual == 1) {
			System.out.println("\nMatrix x is Equal to Matrix y");
		}
		else {
			System.out.println("\nMatrix x is Not Equal to Matrix y");
		}
	}
}
Java Program to Check Matrices are Equal Example

Let me try with different matrixes.

 Enter Matrix Rows & Columns :  
2 2

 Enter the First Matrix Items :  
1 2
3 4

 Enter the Second Matrix Items :  
1 3
3 4

Matrix x is Not Equal to Matrix y