Java compareTo() Method
The compareTo() method is used for two ways of comparison:
- Compares a string with an object.
- Compares two strings lexicographically.
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 first compares the sizes of the corresponding characters (in ASCII order). If the first character and the first character of the argument are different, the comparison ends and returns the difference in theirlengthsIf the first character and the first character of the argument are equal, then the second character is compared with the second character of the argument, and so on, until one of the compared strings ends.
- If the argument string is equal to this string, the return value is 0;
- If this string is lexicographically less than the argument string, a value less than 0 is returned;
- If this string is lexicographically greater than the argument string, a value greater than 0 is returned.
Explanation:
If the first character and the first character of the argument are different, the comparison ends and returns the ASCII code difference of the first character.
If the first character and the first character of the argument are equal, then the second character is compared with the second character of the argument, and so on, until they differ, then the ASCII code difference of that character is returned. If the two strings are of different lengths but their corresponding characters are identical, the difference in length of the two strings is returned.
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 execution result of the above program is:
0
-3
3
Java String class