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

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

Find First Non-Repeating Character in a String in Java

The first non-repeating character is the character that appears only once in the string and whose occurrence comes first.

This problem is frequently asked in interviews and helps understand character frequency and ordered traversal of strings.

How the Logic Works

  1. Create a frequency array to count each character.
  2. Traverse the string and update character counts.
  3. Traverse the string again from left to right.
  4. The first character with frequency 1 is the answer.

Example 1

Input: "programming"

First Non-Repeating Character: p

Example 2

Input: "aabbcc"

Result: No non-repeating character found

Java Program to Find First Non-Repeating Character


import java.util.Scanner;

public class FirstNonRepeatingCharacter {

    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++) {
            char ch = str.charAt(i);
            if (ch != ' ') {
                freq[ch]++;
            }
        }

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch != ' ' && freq[ch] == 1) {
                System.out.println("First Non-Repeating Character: " + ch);
                return;
            }
        }

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

Sample Output


Enter a string: interview
First Non-Repeating Character: n

Enter a string: aabb
No non-repeating character found

Important Notes

Practice Challenges

  1. Find the first non-repeating character without using extra space.
  2. Print all non-repeating characters.
  3. Find the last non-repeating character.

Finding non-repeating characters improves your understanding of frequency analysis and string traversal techniques in Java.