.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
0
is returned ifstringA
is lexicographically less thanstringB
. - A number greater than
0
is returned ifstringA
is 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}}
All contributors
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- robgmerrill124 total contributions
- BrandonDusch580 total contributions
- christian.dinh
- Anonymous contributor
- robgmerrill
- BrandonDusch
Looking to contribute?
- 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.