Java String compareTo()
The java string compareTo() method compares the given string with current string lexicographically. It returns positive number, negative number or 0.
It compares strings on the basis of Unicode value of each character in the strings.
If first string is lexicographically greater than second string, it returns positive number (difference of character value). If first string is less than second string lexicographically, it returns negative number and if first string is lexicographically equal to second string, it returns 0.
Signature
Parameters
anotherString: represents string that is to be compared with current string
Returns
an integer value
Java String compareTo() method example
Output:
0 -5 -1 2
Java String compareTo(): empty string
If you compare string with blank or empty string, it returns length of the string. If second string is empty, result would be positive. If first string is empty, result would be negative.
Output:
5 -2
No comments:
Post a Comment