### Check if a given Matrix is an Identity (Unit) Matrix or not in Java

Note: Identity matrix is a square matrix with 1′s along the diagonal from upper left to lower right and 0′s in all other positions. If it satisfies the structure as explained before then the matrix is called as identity matrix.

public class IdentityMatrix {

public static void main(String args[]) {

int a[][] = new int;
int flag = 1;

Scanner sc = new Scanner(System.in);

System.out.println("Enter elements of Matrix ");

for (int i = 0; i <= 2; i++)
{

for (int j = 0; j <= 2; j++)

{
a[i][j] = sc.nextInt();

}

}
System.out.println("Value of  First Matrix is ");
for (int i = 0; i <= 2; i++)
{

for (int j = 0; j <= 2; j++)

{
System.out.print(a[i][j] + " ");

}

System.out.println();
}

for (int i = 0; i <= 2; i++)

{

for (int j = 0; j <= 2; j++)

{
if (i == j)
{
if (a[i][j] != 1)
{
flag = 0;
break;
}
} else
{
if (a[i][j] != 0)
{
flag = 0;
break;
}
}

}

}

if (flag == 1)

{
System.out.println("It is identity matrix \n");
} else
{
System.out.println("It is not a identity matrix \n");
}
}

}

Output:

(run-1)

Enter First Matrix
1
0
0
0
1
0
0
0
1
Value of  First Matrix is
1 0 0
0 1 0
0 0 1
It is identity matrix

BUILD SUCCESSFUL (total time: 8 seconds)

Output:

(run-2)

Enter First Matrix
1
0
1
0
1
1
0
0
0
Value of  First Matrix is
1 0 1
0 1 1
0 0 0
It is not a identity matrix

BUILD SUCCESSFUL (total time: 10 seconds)