Often, it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to, or greater than the next. A string is less than another if it comes before the other in dictionary order. A string is greater than another if it comes after the other in dictionary order. The String method compareTo() serves this purpose. It has this general form:
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the comparison is returned and is interpreted as shown here:
Value Meaning Less than zero The invoking string is less than str. Greater than zero The invoking string is greater than str. Zero The two strings are equal.
Here is a sample program that sorts an array of strings. The program uses compareTo() to determine sort ordering for a bubble sort:
// A bubble sort for Strings.
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country"
};
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
The output of this program is the list of words:
Now aid all come country for good is men of the the their time to to
As you can see from the output of this example, compareTo() takes into account uppercase and lowercase letters. The word "Now" came out before all the others because it begins with an uppercase letter, which means it has a lower value in the ASCII character set.
If you want to ignore case differences when comparing two strings, use compareToIgnoreCase(), shown here:
int compareToIgnoreCase(String str);
This method returns the same results as compareTo(), except that case differences are ignored. This method was added by Java 2. You might want to try substituting it into the previous program. After doing so, "Now" will no longer be first.