Java String.compareTo() compares two strings lexicographically (in dictionary order) in a case-sensitive manner. For case-insensitive comparison, use compareToIgnoreCase() method.
1. Strings in Lexicographic OrderIf a string 'string1'
comes before another string 'string2'
in the dictionary, then string2
is said to be greater than 'string1'
in string comparison.
string1 > string2
– ‘string1’ comes AFTER ‘string2’ in dictionary.string1 < string2
– ‘string1’ comes BEFORE ‘string2’ in dictionary.string1 = string2
– ‘string1’ and ‘string2’ are equal.The compareTo() function takes one argument of type String. The second string is the String object itself, on which method is called. Note that compareTo() does the string comparison based on the Unicode value of each character in the strings.
int result = string1.compareTo(string2);
The result of this method is in integer value where –
The following Java program compares two strings case-sensitively using the compareTo() method. We ae using Hamcrest matches to assert the return values.
String name = "alex";
//same string
assertThat(name.compareTo("alex"), equalTo(0));
//Different cases
assertThat(name.compareTo("Alex"), greaterThan(0));
assertThat(name.compareTo("ALEX"), greaterThan(0));
//Different strings
assertThat(name.compareTo("alexa"), lessThan(0));
assertThat(name.compareTo("ale"), greaterThan(0));
4. Difference between compareTo() and equals()
The differences between compareTo() and equals() methods are:
Happy Learning !!
Reference: String Java Doc
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4