How to check if String has all unique characters in java

Previous
Next

In this post, we will see if String has all unique characters or not.

There are multiple ways to find if String has all unique characters or not.

By Using HashSet:

  1. You can add each character to HashSet.
  2. If HashSet’s add method returns false then it does not have all unique characters.

Java Program to check if String has all unique characters Using HashSet:

When you run above program, you will get below output:

By using indexOf and lastIndexOf methods.

If indexOf and lastIndexOf returns same value for the character, then it is not repeated in that String.

Java Program to check if String has all unique characters Using indexOf and lastIndexOf:

When you run above program, you will get below output:

By using ascii value of character

It is most efficient of all.
Approach:

  1. Create a boolean array of 26 length
  2. Convert char to uppercase and get its ascii value
  3. Subtract 64 to ascii value to get index between 0 to 25.
  4. If character is not repeated then we should have false in the boolean array

Java Program to check if String has all unique characters:


When you run above program, you will get below output:
Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog