w3resource
Java Programming Exercies

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?



New Content: Composer: Dependency manager for PHP, R Programming