Find First Non-Repeated Character in Java

In this post, we’ll write a Java program to find the first non-repeated character in a string. This is a popular question in coding interviews to test your understanding of string manipulation and hashing.

📌 Problem Statement

Given a string, find the first character that does not repeat anywhere else in the string. Return that character.

📚 Example

  • Input: "programming" → Output: 'p'
  • Input: "aabbcc" → Output: No unique character

✅ Java Program Using LinkedHashMap


import java.util.LinkedHashMap;
import java.util.Map;

public class FirstUniqueCharacter {
    public static void main(String[] args) {
        String input = "programming";
        Character result = findFirstNonRepeated(input);

        if(result != null)
            System.out.println("First non-repeated character is: " + result);
        else
            System.out.println("No unique character found.");
    }

    static Character findFirstNonRepeated(String str) {
        Map charCount = new LinkedHashMap<>();

        for (char c : str.toCharArray()) {
            charCount.put(c, charCount.getOrDefault(c, 0) + 1);
        }

        for (Map.Entry entry : charCount.entrySet()) {
            if (entry.getValue() == 1)
                return entry.getKey();
        }

        return null;
    }
}

✅ Output

First non-repeated character is: p

🧠 Interview Tip

This question can be optimized by using LinkedHashMap for maintaining order. Make sure you explain your choice of data structures clearly.

📌 Conclusion

We’ve learned how to find the first non-repeated character in a string using Java. This logic is commonly used in interviews and string-based challenges.