Java String compareTo
Java String class has two variants of compareTo()
method.
compareTo(String anotherString)
: This compareTo method compares the String object with the String argument passed lexicographically.If String object precedes the argument passed, it returns negative integer and if String object follows the argument String passed, it returns a positive integer.It returns 0 when both the String have same value, in this caseequals(String str)
method will return true.The comparison is based on the Unicode value of each character in the strings. You should check String class source code to check how this method works.
compareToIgnoreCase(String str)
: This compareTo method is similar to the first one, except that it ignores the case. It uses StringCASE_INSENSITIVE_ORDER
Comparator for case insensitive comparison.If the return value of this method is 0 thenequalsIgnoreCase(String str)
will return true. This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.
Java String compareTo Example
Let’s see a small java class explaining the usage of java string compareTo methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.journaldev.util; public class StringCompareToExample { /** * This class show String compareTo examples * @param args */ public static void main(String[] args) { String str = "ABC"; System.out.println(str.compareTo("DEF")); System.out.println(str.compareToIgnoreCase("abc")); } } |
The output of the above compareTo example program is shown below.
Above negative output is because “ABC” is lexicographically less than the “DEF”. The output is -3 because it compares the character values one by one. You can also confirm this with the below test program.
1 2 3 4 5 6 7 8 9 |
public class Test { public static void main(String[] args) { char a="A"; char d = 'D'; System.out.println(a-d); //prints -3 } } |
So when “ABC” is compared to “DEF”, the character at first index is compared. Since they are different and ‘A’ comes before ‘D’ lexicographically, it returns a negative integer with the difference between them, hence the output is -3.
So if you compare “AABC” with “ADBC”, then also you will get the same output as -3. That’s all for Java String compareTo() method example. Note that this method is not the same as the String equals() method.
Reference: Official Oracle Documentation