*85*

# Unique Number in Java Program

The number will be **unique** if it is positive integer and there are no repeated digits in the number. In other words, a number is said to be unique if and only if the digits are not duplicate. For example, 20, 56, 9863, 145, etc. are the unique numbers while 33, 121, 900, 1010, etc. are not unique numbers. In this section, we will create Java programs **to check whether the number is unique or not.**

There are the following ways to check the number is unique or not:

## By Comparing Each Digit Manually

There are the following steps to check number is unique or not:

- Read a number from the user.
- Find the last digit o the number.
- Compare all digits of the number with the last digit.
- If the digit found more than one time, the number is not unique.
- Else, eliminate the last digit of the number.
- Repeat steps 2 to 5 until the number becomes zero.

**UniqueNumberExample1.java**

**Output 1:**

Enter the number you want to check: 13895 The number is unique.

**Output 2:**

Enter the number you want to check: 11100 The number is not unique.

**Output 3:**

Enter the number you want to check: 10000 The number is not unique.

## Using String

Using String, we can also check the number is unique or not. We use the charAt() method of the String to compare each digit of the string.

**UniqueNumberExample2.java**

**Output 1:**

Enter the number you want to check: 9876 The number is unique.

**Output 2:**

Enter the number you want to check: 1010 The number is not unique.

**Output 3:**

Enter the number you want to check: 200 The number is not unique.

In the above program first, we convert the number variable into String by using the toString() method. After that, we determine the length of the string using the length() method.

We have used two for loop (inner and outer) that iterate over the number. Inside the if statement, for each iteration, we have compared the digits by using the **charAt()** method. If both digits are the same, the break statement breaks the execution of the program and prints **the number is not unique**, else prints **the** **number is unique**.

## Using Array

We can also use an array to check the number is unique or not. In this method, we find all the digits of the number and store it into an array. After that, compare the values of all the indexes with each other. If the values are the same, the number is not unique. Remember that before comparing all the indexes we required to declare the size of the array (number of digits).

**UniqueNumberExample3.java**

**Output 1:**

Enter the number you want to check: 898 898 is not a unique number.

**Output 2:**

Enter the number you want to check: 201 201 is a unique number.

**Output 3:**

Enter the number you want to check: 700 700 is not a unique number.