Java program to Find out if String has all Unique Characters?

Here’s a Java program to check if a given string has all unique characters: import java.util.HashSet; public class UniqueCharacterChecker { public static boolean hasAllUniqueCharacters(String str) { if (str == null || str.length() > 128) { // Assuming ASCII characters return false; } HashSet charSet = new HashSet(); for (char ch : str.toCharArray()) { if (!charSet.add(ch)) { return false; // Duplicate character found } } return true; // All characters are unique } public static void main(String[] args) { String testStr = "hello"; // Change this to test other cases System.out.println("Has all unique characters? " + hasAllUniqueCharacters(testStr)); } } Explanation: Uses a HashSet to store characters as we iterate over the string. If a character is already in the set, we return false (indicating a duplicate). If we go through the entire string without finding a duplicate, return true. The time complexity is O(n) and space complexity is O(n). Would you like a version that doesn't use extra space? You said: what is diff between boolean hasAllUniqueCharacters and Boolean hasAllUniqueCharacters ChatGPT said: The difference between boolean hasAllUniqueCharacters and Boolean hasAllUniqueCharacters in Java lies in primitive vs. wrapper types: boolean hasAllUniqueCharacters Primitive type (boolean). Stores only true or false. Cannot be null. More memory-efficient and faster. Example: java Copy Edit boolean flag = true; Boolean hasAllUniqueCharacters Wrapper class (Boolean) from java.lang. Can store true, false, or null. Useful in collections (e.g., List). Requires unboxing when used in conditions (if(Boolean)). Example: java Copy Edit Boolean flag = null; // Allowed, unlike boolean When to Use: Use boolean when you always expect true or false (better performance). Use Boolean when null is a valid state (e.g., database results, optional values). Would you like an example where using Boolean is preferable? You said: yes ChatGPT said: Here's an example where using Boolean (wrapper class) is preferable: Scenario: Handling a Database Query Result Imagine you are querying a database to check if a user is active. However, the database can return null if the status is unknown. In this case, using Boolean (wrapper) instead of boolean (primitive) helps handle null values. Example: java Copy Edit public class User { private Boolean isActive; // Wrapper Boolean allows null public User(Boolean isActive) { this.isActive = isActive; } public Boolean getIsActive() { return isActive; } public static void main(String[] args) { User user1 = new User(true); User user2 = new User(false); User user3 = new User(null); // Status unknown System.out.println("User 1 active: " + user1.getIsActive()); System.out.println("User 2 active: " + user2.getIsActive()); System.out.println("User 3 active: " + user3.getIsActive()); // Can be null } } Why Use Boolean Here? Boolean allows null, which represents an "unknown" or "unset" state. If we used boolean, the value could only be true or false, making it impossible to represent an unknown state. Would you like an example where boolean is the better choice? You said: explain me str.length() > 128 ChatGPT said: The condition str.length() > 128 is used in the context of checking if a string contains all unique characters. Let me explain why: Why 128? The ASCII character set contains 128 unique characters (0-127). If the input string is longer than 128 characters, then at least one character must be repeated (based on the pigeonhole principle). Therefore, if str.length() > 128, we can immediately return false without further checks. Example: java Copy Edit if (str.length() > 128) { return false; // There must be duplicate characters } When is This Useful? When dealing with ASCII characters only. It optimizes performance by avoiding unnecessary character checks if the length already exceeds the limit. What if Using Unicode? The above check is valid only for ASCII (0-127). Unicode has many more characters (over 143,000 as of Unicode 15.0). If handling Unicode, this condition should be removed or adjusted. Would you like an optimized version that supports Unicode? You said: Bref me pigeonhole principle ChatGPT said: Pigeonhole Principle (Basic Idea) The Pigeonhole Principle states that if you put more items into fewer containers than the number of items, at least one container must have more than one item. Example in Simple Terms If you have 5 pigeons and 4 pigeonholes, at least one hole must contain 2 pigeons. Applying to "Unique Characters in a String" The ASCII character set has only 128 unique characters. If a string has more than 128 characters, at least one character must repeat. This is why str.length() > 128 guarantees that the string cannot have all unique characters. Example "abcdefghijklmnopqrstuvw

Mar 8, 2025 - 00:31
 0
Java program to Find out if String has all Unique Characters?

Here’s a Java program to check if a given string has all unique characters:

import java.util.HashSet;

public class UniqueCharacterChecker {
    public static boolean hasAllUniqueCharacters(String str) {
        if (str == null || str.length() > 128) { // Assuming ASCII characters
            return false;
        }

        HashSet charSet = new HashSet<>();
        for (char ch : str.toCharArray()) {
            if (!charSet.add(ch)) {
                return false; // Duplicate character found
            }
        }
        return true; // All characters are unique
    }

    public static void main(String[] args) {
        String testStr = "hello"; // Change this to test other cases
        System.out.println("Has all unique characters? " + hasAllUniqueCharacters(testStr));
    }
}

Explanation:
Uses a HashSet to store characters as we iterate over the string.
If a character is already in the set, we return false (indicating a duplicate).
If we go through the entire string without finding a duplicate, return true.
The time complexity is O(n) and space complexity is O(n).
Would you like a version that doesn't use extra space?

You said:
what is diff between
boolean hasAllUniqueCharacters and Boolean hasAllUniqueCharacters
ChatGPT said:
The difference between boolean hasAllUniqueCharacters and Boolean hasAllUniqueCharacters in Java lies in primitive vs. wrapper types:

  1. boolean hasAllUniqueCharacters Primitive type (boolean). Stores only true or false. Cannot be null. More memory-efficient and faster. Example: java Copy Edit boolean flag = true;
  2. Boolean hasAllUniqueCharacters Wrapper class (Boolean) from java.lang. Can store true, false, or null. Useful in collections (e.g., List). Requires unboxing when used in conditions (if(Boolean)). Example: java Copy Edit Boolean flag = null; // Allowed, unlike boolean When to Use: Use boolean when you always expect true or false (better performance). Use Boolean when null is a valid state (e.g., database results, optional values). Would you like an example where using Boolean is preferable?

You said:
yes
ChatGPT said:
Here's an example where using Boolean (wrapper class) is preferable:

Scenario: Handling a Database Query Result
Imagine you are querying a database to check if a user is active. However, the database can return null if the status is unknown. In this case, using Boolean (wrapper) instead of boolean (primitive) helps handle null values.

Example:
java
Copy
Edit
public class User {
private Boolean isActive; // Wrapper Boolean allows null

public User(Boolean isActive) {
    this.isActive = isActive;
}

public Boolean getIsActive() {
    return isActive;
}

public static void main(String[] args) {
    User user1 = new User(true);
    User user2 = new User(false);
    User user3 = new User(null); // Status unknown

    System.out.println("User 1 active: " + user1.getIsActive());
    System.out.println("User 2 active: " + user2.getIsActive());
    System.out.println("User 3 active: " + user3.getIsActive()); // Can be null
}

}
Why Use Boolean Here?
Boolean allows null, which represents an "unknown" or "unset" state.
If we used boolean, the value could only be true or false, making it impossible to represent an unknown state.
Would you like an example where boolean is the better choice?

You said:
explain me str.length() > 128
ChatGPT said:
The condition str.length() > 128 is used in the context of checking if a string contains all unique characters. Let me explain why:

Why 128?
The ASCII character set contains 128 unique characters (0-127).
If the input string is longer than 128 characters, then at least one character must be repeated (based on the pigeonhole principle).
Therefore, if str.length() > 128, we can immediately return false without further checks.
Example:
java
Copy
Edit
if (str.length() > 128) {
return false; // There must be duplicate characters
}
When is This Useful?
When dealing with ASCII characters only.
It optimizes performance by avoiding unnecessary character checks if the length already exceeds the limit.
What if Using Unicode?
The above check is valid only for ASCII (0-127).
Unicode has many more characters (over 143,000 as of Unicode 15.0).
If handling Unicode, this condition should be removed or adjusted.
Would you like an optimized version that supports Unicode?

You said:
Bref me pigeonhole principle
ChatGPT said:
Pigeonhole Principle (Basic Idea)
The Pigeonhole Principle states that if you put more items into fewer containers than the number of items, at least one container must have more than one item.

Example in Simple Terms
If you have 5 pigeons and 4 pigeonholes, at least one hole must contain 2 pigeons.
Applying to "Unique Characters in a String"
The ASCII character set has only 128 unique characters.
If a string has more than 128 characters, at least one character must repeat.
This is why str.length() > 128 guarantees that the string cannot have all unique characters.
Example
"abcdefghijklmnopqrstuvwxyz" (26 characters) → ✅ Can be unique.
"a quick brown fox jumps over the lazy dog" (43 characters) → ✅ Still possible.
"A string with 200 characters..." → ❌ Must have duplicates (because 200 > 128).
Would you like a coding example demonstrating this principle?

You said:
String str = "a bcd"; this giving result as false
ChatGPT said:
Yes, the string "a bcd" is returning false when checking for unique characters. Let's analyze why:

Breaking Down the String:
The given string is:

plaintext
Copy
Edit
"a bcd"
Characters in the string: 'a', ' ', ' ', 'b', 'c', 'd'
The space character (' ') appears twice.
Since a duplicate character exists, the function correctly returns false.
Code Explanation:
If you're using the HashSet approach to check for unique characters:

java
Copy
Edit
import java.util.HashSet;

public class UniqueCharacterChecker {
public static boolean hasAllUniqueCharacters(String str) {
if (str == null || str.length() > 128) {
return false;
}

    HashSet charSet = new HashSet<>();
    for (char ch : str.toCharArray()) {
        if (!charSet.add(ch)) { // If character is already in the set, return false
            return false;
        }
    }
    return true;
}

public static void main(String[] args) {
    String str = "a  bcd";
    System.out.println("Has all unique characters? " + hasAllUniqueCharacters(str));
}

}
Output:
sql
Copy
Edit
Has all unique characters? false
Why is This Happening?
The space (' ') is considered a character.
Since there are two spaces in "a bcd", it fails the uniqueness check.
Solution:
If you want to ignore spaces while checking for uniqueness, modify the loop:

java
Copy
Edit
if (ch != ' ' && !charSet.add(ch)) {
return false;
}
This will skip spaces while checking for unique characters.

Would you like me to modify the code to ignore spaces or keep them as valid characters?

You said:
Explain me &&
ChatGPT said:
Understanding && (Logical AND) in Java
The && operator in Java is the logical AND operator. It returns true only if both conditions are true. Otherwise, it returns false.

Basic Syntax:
java
Copy
Edit
if (condition1 && condition2) {
// Executes only if both conditions are true
}
Example 1: Checking Two Conditions
java
Copy
Edit
int age = 25;
boolean hasLicense = true;

if (age > 18 && hasLicense) {
System.out.println("You can drive.");
} else {
System.out.println("You cannot drive.");
}
Output:

nginx
Copy
Edit
You can drive.
✅ age > 18 is true
✅ hasLicense is true