Java String compareTo() method example

HQ » Java Tutorial » java.lang » String » compareTo() method example
Java String compareTo() method example 2018-02-19T12:37:45+00:00

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 :


Contact Info


Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.