Java compareTo () method
compareTo () method for comparing two ways:
- String object to be compared with.
- Compares two strings lexicographically.
grammar
int compareTo(Object o) 或 int compareTo(String anotherString)
parameter
o - the object to compare.
anotherString - the string to compare.
return value
- If the argument string is equal to this string, it returns a value of 0;
- If this string is less than the string parameter, it returns a value less than zero;
- If this string is greater than the string parameter, a value greater than 0 is returned.
Examples
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 above program execution results:
0 -3 3