How to Compare Strings in Java Without Case Sensitivity: A Complete Guide with Examples
To compare two strings without considering case sensitivity in Java, you can use the following approaches:
1. Using equalsIgnoreCase()
The String class in Java provides the method equalsIgnoreCase() to compare two strings without considering case.
Example:
Output:
2. Using toLowerCase() or toUpperCase()
You can convert both strings to the same case (e.g., lower or upper) before comparing them using equals().
Example:
Output:
3. Using compareToIgnoreCase()
The compareToIgnoreCase() method compares two strings lexicographically, ignoring case differences.
Example:
Output:
Key Points:
- Use
equalsIgnoreCase()for a straightforward case-insensitive comparison. toLowerCase()ortoUpperCase()allows you to manipulate and compare strings more flexibly.compareToIgnoreCase()is useful for sorting or lexicographical comparison.
No comments:
Post a Comment