Check if a String Has All Unique Characters in Java — Definition, Examples and Program

Learn how to check whether a string contains all unique characters in Java using simple logic, without using advanced data structures or built-in utilities.

Check if a String Has All Unique Characters in Java

A string is said to have all unique characters if no character appears more than once in the string.

This problem is very common in Java interviews and helps test understanding of string traversal, comparison, and logical thinking.

Understanding the Problem

Given a string, we need to:

Example 1

Input: abcde

Output: All characters are unique

Example 2

Input: programming

Output: Characters are NOT unique

Logic Explanation

  1. Use two nested loops to compare characters.
  2. Fix one character and compare it with remaining characters.
  3. If a match is found, stop immediately.
  4. If the loop completes, all characters are unique.

Java Program to Check Unique Characters


import java.util.Scanner;

public class UniqueCharacters {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = sc.nextLine();

        boolean isUnique = true;

        for (int i = 0; i < str.length(); i++) {
            for (int j = i + 1; j < str.length(); j++) {

                if (str.charAt(i) == str.charAt(j)) {
                    isUnique = false;
                    break;
                }
            }

            if (!isUnique) {
                break;
            }
        }

        if (isUnique) {
            System.out.println("All characters are unique");
        } else {
            System.out.println("Characters are NOT unique");
        }
    }
}

Sample Output


Enter a string: abcde
All characters are unique

Enter a string: programming
Characters are NOT unique

Important Notes

Practice Challenges

  1. Check unique characters ignoring case sensitivity.
  2. Use a frequency array to optimize the program.
  3. Check unique characters using HashSet.

This problem strengthens nested loop logic and builds a strong foundation for more advanced string manipulation techniques.