DEV Community

Automation Ninja
Automation Ninja

Posted on

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<Character> 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));
    }
}

Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

}
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<Character> 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));
}
Enter fullscreen mode Exit fullscreen mode

}
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
🔹 Since both are true, the condition inside if executes.

Example 2: One Condition is False
java
Copy
Edit
int age = 16;
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 cannot drive.
❌ age > 18 is false
✅ hasLicense is true
🔹 Since one condition is false, the whole && condition fails.

Short-Circuiting with &&
Java uses short-circuit evaluation with &&.
If the first condition is false, the second condition is not even checked.
Example:

java
Copy
Edit
int x = 5;
if (x > 10 && someMethod()) {

System.out.println("Condition met");
}

public static boolean someMethod() {
System.out.println("someMethod() called");
return true;
}
Output:

scss
Copy
Edit
(nothing)
Since x > 10 is false, someMethod() is never called.
Example in Your Context:
java
Copy
Edit
if (ch != ' ' && !charSet.add(ch)) {
return false;
}
🔹 First Condition: ch != ' ' → Ensures spaces are ignored.
🔹 Second Condition: !charSet.add(ch) → Checks if the character is already in the set.

How it Works?

If ch is a space (' '), the && condition fails, and !charSet.add(ch) is not checked.
If ch is not a space, then !charSet.add(ch) is evaluated to check for duplicates.
Would you like examples with || (logical OR) as well? 😊

You said:
will && work for String str = "abcd";?
ChatGPT said:
Yes, the && (logical AND) operator will work for the string "abcd", but it depends on how you use it in a condition. Let’s analyze different cases.

Example 1: Checking Unique Characters (&& in a Loop)
If you use && inside a loop to check for unique characters:

java
Copy
Edit
import java.util.HashSet;

public class UniqueCharacterChecker {
public static boolean hasAllUniqueCharacters(String str) {
HashSet charSet = new HashSet<>();

    for (char ch : str.toCharArray()) {
        if (ch != ' ' && !charSet.add(ch)) { 
            return false; // Duplicate character found (excluding spaces)
        }
    }
    return true;
}

public static void main(String[] args) {
    String str = "abcd";
    System.out.println("Has all unique characters? " + hasAllUniqueCharacters(str));
}
Enter fullscreen mode Exit fullscreen mode

}
✅ Output:

sql
Copy
Edit
Has all unique characters? true
The && ensures that spaces are ignored before checking for duplicates.
Since "abcd" has all unique characters, it returns true.
Example 2: Direct Comparison (&& in an If Condition)
You can use && to check multiple conditions in an if statement:

java
Copy
Edit
String str = "abcd";

if (str.length() > 0 && str.charAt(0) == 'a') {
System.out.println("String starts with 'a' and is not empty.");
}
✅ Output:

vbnet
Copy
Edit
String starts with 'a' and is not empty.
str.length() > 0 ensures the string is not empty.
str.charAt(0) == 'a' checks if it starts with 'a'.
Both must be true for the message to print.
Example 3: Short-Circuiting Behavior
Let’s check how && short-circuits execution:

java
Copy
Edit
public class Test {
public static void main(String[] args) {
String str = "abcd";

    if (str.length() > 10 && str.charAt(10) == 'z') {
        System.out.println("Valid condition");
    } else {
        System.out.println("Condition failed");
    }
}
Enter fullscreen mode Exit fullscreen mode

}
✅ Output:

sql
Copy
Edit
Condition failed
str.length() > 10 is false, so str.charAt(10) is never executed.
This prevents an IndexOutOfBoundsException.
Conclusion
Yes, && will work with "abcd" as long as:

It's inside a logical condition (if, for, etc.).
Both conditions involve boolean expressions.
The first condition is true for the second to execute.
Would you like more examples with && in different scenarios? 😊

You said:
Explain ch != ' '
ChatGPT said:
Understanding ch != ' ' in Java
ch != ' ' is a condition that checks if a character is NOT a space (' ').

Breaking it Down
ch is a char variable representing a single character.
' ' is a space character (ASCII code 32).
!= means "not equal to".
ch != ' ' returns:
true → if ch is not a space.
false → if ch is a space.
Example 1: Filtering Out Spaces
java
Copy
Edit
public class SpaceCheck {
public static void main(String[] args) {
char ch1 = 'a';
char ch2 = ' ';

    System.out.println(ch1 != ' '); // true (because 'a' is not a space)
    System.out.println(ch2 != ' '); // false (because ' ' is a space)
}
Enter fullscreen mode Exit fullscreen mode

}
✅ Output:

arduino
Copy
Edit
true
false
Example 2: Removing Spaces from a String
java
Copy
Edit
public class RemoveSpaces {
public static void main(String[] args) {
String str = "a b c d";
StringBuilder result = new StringBuilder();

    for (char ch : str.toCharArray()) {
        if (ch != ' ') { // Ignore spaces
            result.append(ch);
        }
    }

    System.out.println("String without spaces: " + result);
}
Enter fullscreen mode Exit fullscreen mode

}
✅ Output:

arduino
Copy
Edit
String without spaces: abcd
Example 3: Checking Unique Characters (Ignoring Spaces)
If we modify the unique character check to ignore spaces:

java
Copy
Edit
import java.util.HashSet;

public class UniqueCharacterChecker {
public static boolean hasAllUniqueCharacters(String str) {
HashSet charSet = new HashSet<>();

    for (char ch : str.toCharArray()) {
        if (ch != ' ' && !charSet.add(ch)) { 
            return false; // Duplicate character found (excluding spaces)
        }
    }
    return true;
}

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

}
✅ Output:

sql
Copy
Edit
Has all unique characters? true
Without ch != ' ', it would return false because of the space.
With ch != ' ', spaces are ignored when checking for uniqueness.
When to Use ch != ' '
✅ When you want to skip spaces while processing characters.
✅ When checking for unique characters without considering spaces.
✅ When filtering or cleaning a string before further processing.

Would you like to see an example that also ignores punctuation or special characters? 😊

You said:
give me result with dry run for
String str = "a bcd";
String str = "a bcd";
String str = "abcd";
ChatGPT said:
Let's do a dry run for the given strings using the unique character check method with the condition ch != ' ' && !charSet.add(ch).

Code for Reference
java
Copy
Edit
import java.util.HashSet;

public class UniqueCharacterChecker {
public static boolean hasAllUniqueCharacters(String str) {
HashSet charSet = new HashSet<>();

    for (char ch : str.toCharArray()) {
        if (ch != ' ' && !charSet.add(ch)) { 
            return false; // Duplicate character found (excluding spaces)
        }
    }
    return true;
}

public static void main(String[] args) {
    String[] testStrings = {"a bcd", "a  bcd", "abcd"};

    for (String str : testStrings) {
        System.out.println("Input: \"" + str + "\" → Has all unique characters? " + hasAllUniqueCharacters(str));
    }
}
Enter fullscreen mode Exit fullscreen mode

}
Dry Run for Each String
1️⃣ String str = "a bcd"
Characters: 'a', ' ', 'b', 'c', 'd'

Step Character (ch) ch != ' ' charSet.add(ch) Condition ch != ' ' && !charSet.add(ch) Action
1 'a' ✅ true ✅ true ❌ false (no duplicate) Add to set
2 ' ' (space) ❌ false - - Ignore
3 'b' ✅ true ✅ true ❌ false (no duplicate) Add to set
4 'c' ✅ true ✅ true ❌ false (no duplicate) Add to set
5 'd' ✅ true ✅ true ❌ false (no duplicate) Add to set
✅ Result: true (all unique characters, spaces ignored)

2️⃣ String str = "a bcd"
Characters: 'a', ' ', ' ', 'b', 'c', 'd'

Step Character (ch) ch != ' ' charSet.add(ch) Condition ch != ' ' && !charSet.add(ch) Action
1 'a' ✅ true ✅ true ❌ false (no duplicate) Add to set
2 ' ' (space) ❌ false - - Ignore
3 ' ' (space) ❌ false - - Ignore
4 'b' ✅ true ✅ true ❌ false (no duplicate) Add to set
5 'c' ✅ true ✅ true ❌ false (no duplicate) Add to set
6 'd' ✅ true ✅ true ❌ false (no duplicate) Add to set
✅ Result: true (all unique characters, spaces ignored)

3️⃣ String str = "abcd"
Characters: 'a', 'b', 'c', 'd'

Step Character (ch) ch != ' ' charSet.add(ch) Condition ch != ' ' && !charSet.add(ch) Action
1 'a' ✅ true ✅ true ❌ false (no duplicate) Add to set
2 'b' ✅ true ✅ true ❌ false (no duplicate) Add to set
3 'c' ✅ true ✅ true ❌ false (no duplicate) Add to set
4 'd' ✅ true ✅ true ❌ false (no duplicate) Add to set
✅ Result: true (all unique characters)

Final Results
Input String Output
"a bcd" ✅ true
"a bcd" ✅ true
"abcd" ✅ true
Key Takeaways
Spaces are ignored in uniqueness checks due to ch != ' '.
All three cases return true because all non-space characters are unique.
If spaces were not ignored, "a bcd" would return false because of duplicate spaces.

Top comments (0)