java.lang.String compareTo()

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 :


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.

Sample Output :

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

java string compareTo method example

java string compareTo method example

Exception Scenario :

No notable exception scenario as indicated on JAVA API.

Suggested Reading List :