Java program to find the first non-repeating character in a string


import java.util.HashMap;

public class FirstNonRepeatingCharacter {

public static char firstNonRepeatingCharacter(String str) {
    HashMap<Character, Integer> charCountMap = new HashMap<>();
    for (char c : str.toCharArray()) {
        charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
    }

    for (char c : str.toCharArray()) {
        if (charCountMap.get(c) == 1) {
            return c;
        }
    }

    return '\0';
}

public static void main(String[] args) {
    String str = "hello world";
    char nonRepeatingCharacter = firstNonRepeatingCharacter(str);
    System.out.println("The first non-repeating character in the string \"" + str + "\" is: " + nonRepeatingCharacter);
}

}

This program works by first creating a hash map to store the frequency of each character in the string. Then, it iterates through the string and checks if the frequency of each character is 1. If it is, then the character is non-repeating and the program returns it. Otherwise, the program continues iterating through the string.

If the program reaches the end of the string without finding any non-repeating characters, then it returns ‘\0’, which is the null character.

Leave a comment