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:
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:
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?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework