w3resource

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

Java Basic: Exercise-141 with Solution

Write a Java program to check if a given string has all unique 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) {
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        for (int i = 1; i < chars.length; ++i) {
            if (chars[i] == chars[i-1]) {
                return false;
            }
        }
        return true;
    }
public static void main(String[] args) {
		//String str = "xyz";
		String str = "xyyz";
		System.out.println("Original String : "+str);
		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.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to get the index of the first number and the last number of a subarray where the sum of numbers is zero from a given array of integers.
Next: Write a Java program to check if two given strings are anagrams or not.

What is the difficulty level of this exercise?



Java: Tips of the Day

Try and catch:

Java is excellent at catching errors, but it can only recover gracefully if you tell it what to do. The cascading hierarchy of attempting to perform an action in Java starts with try, falls back to catch, and ends with finally. Should the try clause fail, then catch is invoked, and in the end, there's always finally to perform some sensible action regardless of the results. Here's an example:

try {
        cmd = parser.parse(opt, args); 
       
        if(cmd.hasOption("help")) {
                HelpFormatter helper = new HelpFormatter();
                helper.printHelp("Hello ", opt);
                System.exit(0);
                }
        else {
                if(cmd.hasOption("shell") || cmd.hasOption("s")) {
                String target = cmd.getOptionValue("tgt");
                } // else
        } // fi
} catch (ParseException err) {
        System.out.println(err);
        System.exit(1);
        } //catch
        finally {
                new Hello().helloWorld(opt);
        } //finally
} //try

It's a robust system that attempts to avoid irrecoverable errors or, at least, to provide you with the option to give useful feedback to the user. Use it often, and your users will thank you!

Ref: https://red.ht/3EZc9OC