There are two types to use java String.compareTo():
- string compare with an object.
2.compare two string in character order.
Signature
1 2 |
int compareTo(Object o) int compareTo(String anotherString) |
Arguments
- o –an object to campere with.
- anotherString — a string to compare with.
Return
This two methods will return an integer number.First,they compare the character which in given Strings by order,if the first character is not same as the first character of the argument string,the compare process will stop and return length difference of this two string,if the first character is same as the first character of the argument string,than will continue to get their second character to compare to each other,and so on until one of the characters being compared or compared ends.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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 is
1 2 3 |
0 -3 3 |