YouTip LogoYouTip

Java String Compareto

# Java compareTo() Method [![Image 3: Java String Class](#)Java String Class](#) * * * The compareTo() method is used for comparison in two ways: * Comparing a string with an object. * Comparing 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 corresponding characters (in ASCII code order). If the first character is not equal to the first character of the parameter, the comparison ends, and the **difference** in their lengths is returned. If the first character is equal to the first character of the parameter, the second character is compared with the second character of the parameter, and so on, until a character is found that is not equal or one of the strings ends. * If the parameter string is equal to this string, the return value is 0; * If this string is lexicographically less than the string parameter, a value less than 0 is returned; * If this string is lexicographically greater than the string parameter, a value greater than 0 is returned. > **Note:** > > > If the first character is not equal to the first character of the parameter, the comparison ends, and the ASCII code difference of the first characters is returned. > > > If the first character is equal to the first character of the parameter, the second character is compared with the second character of the parameter, and so on, until they are not equal, and the ASCII code difference of those characters is returned. If the two strings have different lengths but the corresponding characters are exactly the same, the difference in the lengths 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 output of the above program is: 0-33 * * Java String Class](#)
← Java String ConcatCharacter Tostring β†’