Java String compareTo() method compares two strings lexicographically. It compares the characters of two strings one by one, starting from the first character. If the first character of the first string is less than the first character of the second string, then compareTo() method returns a negative integer. If the first character of the first string is greater than the first character of the second string, then compareTo() method returns a positive integer. If the first characters of both strings are equal, then compareTo() method moves to the next characters and continues the comparison until it reaches the end of one of the strings.
The syntax of the compareTo() method is as follows:
public int compareTo(String str)
Here, str is the string to be compared with the current string.
The compareTo() method returns an integer value that indicates the lexicographic relation between the two strings. If the current string is lexicographically greater than the argument string, then a positive integer is returned. If the current string is lexicographically less than the argument string, then a negative integer is returned. If the two strings are equal, then the method returns 0.
Here's an example:
String str1 = "hello";
String str2 = "world";
int result = str1.compareTo(str2);
if (result < 0) {
System.out.println("str1 is less than str2");
} else if (result > 0) {
System.out.println("str1 is greater than str2");
} else {
System.out.println("str1 and str2 are equal");
}
In this example, str1 is compared with str2 using the compareTo() method. Since str1 is lexicographically less than str2, the method returns a negative integer, and the output will be "str1 is less than str2".