Java .compareToIgnoreCase()
The compareToIgnoreCase() method compares two strings lexicographically based on the Unicode value of each character in the string while ignoring lower case and upper case differences.
A value of 0 will be returned if equal to comparison, less than 0 if the string is lexicographically less, and greater than 0 if the string is lexicographically greater.
Syntax
stringA.compareToIgnoreCase(stringB);
Both stringA and stringB are required in order for the .compareTo() method to work properly.
A value of 0 will be returned if the strings are equal. Otherwise, the following will happen:
- A number less than
0is returned ifstringAis lexicographically less thanstringB. - A number greater than
0is returned ifstringAis lexicographically more thanstringB.
Through the CASE_INSENSITIVE_ORDER field of the String class, upper and lower case characters effectively hold the same Unicode value (e.g., “a” - “A” = 0).
Note: To take case into account, the .compareTo() method should be used. Alternatively, the .equals() method can be used to compare strings without taking Unicode values into account.
Example 1
Compare "Codecademy" to "Codecademy":
class CompareStringsIgnoreCase {public static void main(String[] args) {String word1 = "Codecademy";String word2 = "Codecademy";System.out.println(word1.compareToIgnoreCase(word2));// Output: 0}}
Example 2
Compare "Codecademy" to "codecademy":
class CompareStringsIgnoreCase {public static void main(String[] args) {String word1 = "Codecademy";String word2 = "codecademy";System.out.println(word1.compareToIgnoreCase(word2));// Output: 0}}
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours