The compareTo() method compares two strings lexicographically according to the dictionary. The comparison is based on the Unicode value of each character in the strings.
public int compareTo(String argumentString)
It returns zero if the two strings are lexicographically equal. It returns a negative number if the invoking String object lexicographically precedes the argument string. It returns a positive number if the invoking String object lexicographically follows the argument string.
- If two strings are different then this method returns this.charAt(index)-argumentString.charAt(index) where index is the smallest index at which the two strings have different characters.
- If there is no position where they differ, then the shorter string precedes the longer string. Here it returns this.length()-argumentString.length() .
The following program illustrates this method:
String CompareTo Demo
class CompareToTest
{
public static void main(String[] args)
{
String str1 = "The best way to predict your future is to create it";
String str2 = "The best way to predict ";
String str3 = "your future is to create it";
//comparing str1 with str2 + str3
compare(str1, str2 + str3); // LINE A
//comparing str1 with str2
compare(str1, str2); // LINE B
//comparing str1 with str3
compare(str1, str3); // LINE C
}
public static void compare(String one, String two)
{
int result = one.compareTo(two);
if (result == 0)
{
System.out.print("Invoking string and argument string are equal.");
}
else if (result < 0)
{
System.out.print("The invoking string follows the argument string.");
}
else
{
System.out.print("The invoking string precedes the argument string.");
}
System.out.println(" The comparision value is : " + result);
}
}
OUTPUTInvoking string and argument string are equal. The comparision value is : 0
The invoking string precedes the argument string. The comparision value is : 27
The invoking string follows the argument string. The comparision value is : -37
DESCRIPTIONIn the first comparision both the strings are lexicographically equal, 0
is returned at LINE A
.
At LINE B
, case 2, as mentioned above holds. str2
lexicographically precedes str1
. The difference of the lengths is returned.
At LINE C
, str1
precedes str3
as 'T' precedes 'y' in the unicode character list. It returns the difference of the unicode values of 'T' and 'y' i.e. -37
.
THINGS TO TRY
- Compare two similar strings, one in lowercase and the other in uppercase.
For e.g., "Learn Java" vs "LEARN JAVA".
The compareToIgnoreCase() method compares two strings ignoring the case differences.