First non-repeated character in a String in Java

We have to find the first non-repeating character from given string. For example, if the given string is “hello” then the output should be “h” because except “l” all are non-repeated.

Example – Program to find first non-repeated character

class NonRepeatingChar {
  static final int NO_OF_CHARS = 128;

  static char indexCount[] = new char[NO_OF_CHARS];

  static int firstNonRepeatingCharacter(String originalString) {
    for (int i = 0; i < originalString.length(); i++) {
      indexCount[originalString.charAt(i)]++;
    }
    int index = -1;
  
    for (int i = 0; i < originalString.length(); i++) {
      if (indexCount[originalString.charAt(i)] == 1) {
        index = i;
        break;
      }
    }

    return index;
  }

  public static void main(String[] args) {
    String originalString = "hello";
    int valueIndex = firstNonRepeatingCharacter(originalString);
    if (valueIndex == -1) {
      System.out.println("Either all characters are repeating or empty string");
    } else {
      System.out.println("First non-repeating character is : " + originalString.charAt(valueIndex));

    }

  }
}

Output

First non-repeating character is : h

Example – Another way

public class NonRepeatingChar {
  public static void main(String[] args) {
    String originalString = "hello";
    for (int i = 0; i < originalString.length(); i++) {
      boolean index = true;
      for (int j = 0; j < originalString.length(); j++) {
        if (i != j && originalString.charAt(i) == originalString.charAt(j)) {
          index = false;
          break;
        }
      }
      if (index) {
        System.out.println("The first non repeated character is: " + originalString.charAt(i));
        break;
      }
    }
  }
}

Output

The first non repeated character is: h