Java compareTo() Method
The compareTo() method is used for comparison in two ways:
- Compare a string with an object.
- Compare two strings lexicographically.
Syntax
Parameters
o-- The object to be compared.
anotherString-- The string to be compared.
Return Value
The return value is an integer. It first compares the size of corresponding characters (in ASCII code order). If the first character is not equal to the first character of the parameter, the comparison ends, and returns the length between them.difference, if the first character is equal to the first character of the parameter, then compare the second character with the second character of the parameter, and so on, until one of the compared strings ends.
- If the parameter string is equal to this string, return value 0;
- If this string is less than the string parameter, return a value less than 0;
- If this string is greater than the string parameter, return a value greater than 0.
Explanation:
If the first character is not equal to the first character of the parameter, end the comparison and return the ASCII code difference of the first character.
If the first character is equal to the first character of the parameter, then compare the second character with the second character of the parameter, and so on, until they are not equal, and return the ASCII code difference of that character. If the two strings are of different lengths, but the corresponding characters are exactly the same, then return the length difference between the two strings.
Example
The above program execution result is:
0 -3 3
Other Extensions
Java String Class