Identity Matrix Program in Java

In this article, you will learn how to find a Matrix is an Identity Matrix or not using Java. An identity matrix is a special type of square matrix where all diagonal elements are 1, and all other elements are 0.

Here’s a Java program to check if a given square matrix is an identity matrix:

package com.javacodepoint.array.multidimensional;

public class IdentityMatrix {

	public static boolean isIdentityMatrix(int[][] matrix) {

		if (matrix == null || matrix.length == 0 || matrix.length != matrix[0].length) {
			return false; // If the matrix is not square or it's null/empty, it can't be an identity
							// matrix.
		}

		int n = matrix.length;

		// Check diagonal elements are 1 and all other elements are 0
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (i == j) {
					if (matrix[i][j] != 1) {
						return false;
					}
				} else {
					if (matrix[i][j] != 0) {
						return false;
					}
				}
			}
		}

		return true;
	}

	public static void main(String[] args) {
		int[][] matrix1 = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } };

		int[][] matrix2 = { { 1, 0, 1 }, { 0, 1, 0 }, { 0, 0, 1 } };

		System.out.println("Matrix:");
		for (int[] row : matrix1) {
			for (int value : row) {
				System.out.print(value + " ");
			}
			System.out.println();
		}
		System.out.println("Is Identity Matrix: " + isIdentityMatrix(matrix1));

		System.out.println("\nMatrix:");
		for (int[] row : matrix2) {
			for (int value : row) {
				System.out.print(value + " ");
			}
			System.out.println();
		}
		System.out.println("Is Identity Matrix: " + isIdentityMatrix(matrix2));
	}
}

OUTPUT:

Matrix:
1 0 0
0 1 0
0 0 1
Is Identity Matrix: true

Matrix:
1 0 1
0 1 0
0 0 1
Is Identity Matrix: false

Explanation:

In this program, we have a static method isIdentityMatrix, which takes a 2D integer array (matrix) as input and returns a boolean value indicating whether the matrix is an identity matrix or not.

In the isIdentityMatrix method, we first check if the matrix is square and not null or empty. If it’s not square or is null/empty, we immediately return false, as it can’t be an identity matrix.

Next, we iterate through the matrix using nested loops. For each element, we check if it lies on the main diagonal (i == j). If so, it should be 1; otherwise, it should be 0. If any element does not meet these criteria, we return false, indicating that the matrix is not an identity matrix. Otherwise, we return true.

Learn also: Find the Largest Element in a Matrix.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *