Java String compareTo() method example

Description :

This java tutorial focuses on the compareTo() method of String class. This method returns an int value based on the unicode equivalent on each character between the string and the parameter String input str. It gives an output of 0 if the two strings are equal. The output of less than zero gives that the invoking string less than the method argument while an output of positive integer indicates that the invoking string is greater than the method argument.

Method Syntax :

public int compareTo(String str)

Parameter input :

  • str – This method accepts only one input which is in String data type.

Method Returns :

This method returns an int datatype based on the lexicographical comparison between two strings

Exception :

None

Java Code Example :

This example source code shows the usage of compareTo method of String class and also we have included several possible declaration of String. This code just simple compare our parent string to our String argument.

public class StringCompareToDemo {
    /*
     * This java source code shows the use of compareTo() method of String class
     */

    public static void main(String[] args) {
        System.out.println("bc".compareTo("bac"));
        System.out.println("e".compareTo("test"));
        System.out.println("test".compareTo("tests"));
        String firstString = "Hello";
        String str = new String("ew");
        System.out.println(firstString.compareTo(str));

    }
}

Sample Output :

Running the compareTo() example source code will give you the following output

Exception Scenario :

No notable exception scenario as indicated on JAVA API.

Suggested Reading List :