Find First Repeating Character in a String in Java — Definition, Examples and Program

Learn how to find the first repeating character in a string using Java. This blog explains the logic, examples, and a clean Java program with practice challenges.

Find First Repeating Character in a String in Java

The first repeating character in a string is the character that appears more than once and whose second occurrence comes first in the string order.

This problem is commonly asked in interviews and helps improve understanding of string traversal and character frequency.

How the Logic Works

  1. Create a frequency array to track visited characters.
  2. Traverse the string from left to right.
  3. If a character is seen again, it is the first repeating character.
  4. Stop the traversal immediately.

Example 1

Input: "programming"

First Repeating Character: r

Example 2

Input: "abcdef"

Result: No repeating character found

Java Program to Find First Repeating Character


import java.util.Scanner;

public class FirstRepeatingCharacter {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

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

        boolean[] visited = new boolean[256];

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            if (ch == ' ') {
                continue;
            }

            if (visited[ch]) {
                System.out.println("First Repeating Character: " + ch);
                return;
            }

            visited[ch] = true;
        }

        System.out.println("No repeating character found");
    }
}

Sample Output


Enter a string: coding
No repeating character found

Enter a string: interview
First Repeating Character: i

Important Notes

Practice Challenges

  1. Find the first repeating character without using extra space.
  2. Find the last repeating character.
  3. Print all repeating characters in order of appearance.

Finding the first repeating character improves your ability to optimize string traversal and early termination logic.