w3resource

Java: Check if a given string has all unique characters


Check Distinct Characters

Write a Java program to check if a given string has all distinct characters.

Pictorial Presentation:

Java Basic Exercises: Check if a given string has all unique characters.


Sample Solution:

Java Code:

import java.util.*;
public  class Solution {
    /**
     * @param str: a string
     * @return: a boolean
     */
    public static boolean is_Unique_str(String str) {
        // Convert the input string to a character array
        char[] chars = str.toCharArray();
        
        // Sort the character array in lexicographical order
        Arrays.sort(chars);
        
        // Check for repeated characters in the sorted array
        for (int i = 1; i < chars.length; ++i) {
            if (chars[i] == chars[i-1]) {
                return false;
            }
        }
        
        // If no repeated characters are found, the string is considered to have all unique characters
        return true;
    }
    
    public static void main(String[] args) {
        // Test case: Check if the string "xyyz" has all unique characters
        // Note: You can change the value of the 'str' variable for different input strings.
        String str = "xyyz";
        
        // Print the original string
        System.out.println("Original String : " + str);
        
        // Check if the string has all unique characters and print the result
        System.out.println("String has all unique characters: " + is_Unique_str(str));
    }   
}

Sample Output:

Original String : xyyz
String has all unique characters: false

Flowchart:

Flowchart: Java exercises: Check if a given string has all unique characters.


For more Practice: Solve these Related Problems:

  • Write a Java program to check if a given string has all distinct characters without using additional data structures.
  • Write a Java program to determine the minimum number of characters that need to be removed to make a string contain all distinct characters.
  • Write a Java program to check if two strings contain exactly the same set of distinct characters.
  • Write a Java program to find the first repeated character in a given string.

Go to:


PREV : Merge Overlapping Intervals.
NEXT : Check Anagrams.


Java Code Editor:

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.