Find Duplicate Characters in a String in Java — Definition, Examples and Program

Learn how to find duplicate characters in a string using Java. This blog explains the concept, examples, and an efficient Java program using character frequency.

Find Duplicate Characters in a String in Java

Finding duplicate characters in a string means identifying characters that appear more than once. This problem is commonly asked in interviews and helps in understanding character frequency and string traversal.

Duplicate character detection is useful in:

How the Logic Works

  1. Create a frequency array to store character counts.
  2. Traverse the string character by character.
  3. Increment the count for each character.
  4. Print characters whose count is greater than 1.

Example 1

Input: "programming"

Duplicate Characters:

Example 2

Input: "Java"

Duplicate Characters:

Java Program to Find Duplicate Characters


import java.util.Scanner;

public class DuplicateCharacters {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

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

        int[] freq = new int[256];

        for (int i = 0; i < str.length(); i++) {
            freq[str.charAt(i)]++;
        }

        System.out.println("Duplicate Characters:");

        for (int i = 0; i < 256; i++) {
            if (freq[i] > 1 && i != ' ') {
                System.out.println((char) i);
            }
        }
    }
}

Sample Output


Enter a string: interview
Duplicate Characters:
i
e

Important Notes

Practice Challenges

  1. Print duplicate characters with their frequency.
  2. Find duplicate characters without using arrays.
  3. Print only the first repeating character.

Duplicate character detection strengthens your understanding of frequency counting and efficient string processing in Java.