# Java create Identity matrix

In this tutorial, you will learn how to create an identity or unit matrix.

## Java create Identity matrix

In this tutorial, you will learn how to create an identity or unit matrix.

An identity matrix is a square matrix, of size n x n in which all the elements of the principal diagonal are ones and all other elements are zeros. Here, we are going to create the unit matrix of arbitrary dimensions say (n*n). The given code accepts the size(n) of unit matrix and display the matrix of  n x n. Suppose, n is 3, then the unit matrix of size 3 x 3 should be:

```1 0 0
0 1 0
0 0 1
```

Example:

```import java.util.*;
class UnitMatrix
{
public static int[][] create(int size) {
int[][] matrix = new int[size][size];
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
matrix[i][j] = (i == j) ? 1 : 0;
return matrix;
}

public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter size of matrix: ");
int size=input.nextInt();
int matrix[][]=create(size);

for (int i=0 ; i < matrix.length ; i++)
{ System.out.println();
for (int j=0 ; j < matrix[i].length ; j++){
System.out.print(matrix[i][j]+" ");
}
}
}
}
```

Output:

```Enter size of matrix:
5

1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
```