w3resource

Java: Find first non repeating character in a string


39. First Non-Repeating Character

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

Visual Presentation:

Java String Exercises: Find first non repeating character in a string


Sample Solution:

Java Code:

// Importing necessary Java utilities.
import java.util.*;

// Define a class named Main.
public class Main {
    
    // Main method to execute the program.
    public static void main(String[] args) {
        // Declare and initialize a string variable.
        String str1 = "gibblegabbler";
        
        // Print the original string.
        System.out.println("The given string is: " + str1);
        
        // Loop through each character of the string.
        for (int i = 0; i < str1.length(); i++) {
            // Assume the character at index 'i' is unique initially.
            boolean unique = true;
            
            // Loop through the string again to compare characters.
            for (int j = 0; j < str1.length(); j++) {
                // Check if the characters at positions 'i' and 'j' are the same but not at the same index.
                if (i != j && str1.charAt(i) == str1.charAt(j)) {
                    // If found, set unique to false and break the loop.
                    unique = false;
                    break;
                }
            }
            
            // If the character at index 'i' is unique, print it and exit the loop.
            if (unique) {
                System.out.println("The first non-repeated character in the String is: " + str1.charAt(i));
                break;
            }
        }
    }
}

Sample Output:

The given string is: gibblegabbler
The first non repeated character in String is: i

Flowchart:

Flowchart: Java String  Exercises - Find first non repeating character in a string



For more Practice: Solve these Related Problems:

  • Write a Java program to identify the first non-repeating character in a string using an efficient algorithm.
  • Write a Java program to find the first non-repeating character in a string and return its index.
  • Write a Java program to detect the first unique character in a string and then remove it from the string.
  • Write a Java program to determine the first non-repeating character in a string after converting it to lowercase.

Go to:


PREV : Remove Duplicate Characters.
NEXT : Divide String into Equal Parts.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.