Java String compareTo()

Filed Under: Java

Java String compareTo() method is used to compare two strings lexicographically. This method is declared in Comparable interface. Since String implements Comparable interface, it provides compareTo() method implementation.

Java String compareTo

Java String class has two variants of compareTo() method.

  1. 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 case equals(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.

  2. compareToIgnoreCase(String str): This compareTo method is similar to the first one, except that it ignores the case. It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison.

    If the return value of this method is 0 then equalsIgnoreCase(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.


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.

java string compareTo, string compareTo java example

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.


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.

You can checkout more core java examples from our GitHub Repository.

Reference: Official Oracle Documentation

Comments

  1. samp says:

    i gave another string as abc with compareTo but i got -32 as output could u tell me how it comes.i know its comapring with casesensitive but how -32 i can get i am unable to know.here is my scenario
    String str = “ABC”;
    System.out.println(str.compareTo(“abc”));
    System.out.println(str.compareToIgnoreCase(“abc”));

    1. javababu says:

      ASCII value of “a” 97 and “A” is 65
      so, A-a = 65 – 97 = -32

  2. tanmay says:

    What’s the benefit over equals method?

  3. Sunil says:

    What does that mean if ” value is zero” ?

    1. Pankaj says:

      Sorry for confusion, i meant if return value is 0. I have updated the post for more clarity.

    2. Rameshkumar says:

      it means both strings are equal.(i.e ASCII value are same)

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages