Java compareTo() Method
The compareTo() method is used for two types of comparisons:
Comparison of a string with an object.
Lexicographical comparison of two strings.
Syntax
int compareTo(Object o)
or
int compareTo(String anotherString)
Parameters
o -- The object to be compared.
anotherString -- The string to be compared.
Return Value
The return value is an integer. It compares the characters based on their ASCII values. If the first characters of both strings are not equal, the comparison ends and returns the difference in their lengths. If the first characters are equal, it proceeds to compare the second characters, and so on, until one of the strings ends.
If the string is equal to the string argument, it returns 0.
If the string is less than the string argument, it returns a value less than 0.
If the string is greater than the string argument, it returns a value greater than 0.
Note:
If the first characters of both strings are not equal, the comparison ends and returns the difference in their ASCII values.
If the first characters are equal, it proceeds to compare the second characters, and so on, until they are not equal, and returns the difference in their ASCII values.
If both strings are of different lengths but have identical characters up to the length of the shorter string, it returns the difference in their lengths.
Example
public class Test {
public static void main(String args[]) {
String str1 = "Strings";
String str2 = "Strings";
String str3 = "Strings123";
int result = str1.compareTo(str2);
System.out.println(result);
result = str2.compareTo(str3);
System.out.println(result);
result = str3.compareTo(str1);
System.out.println(result);
}
}
The output of the above program is:
0
-3
3