Java String compareTo()

Java String.compareTo() compares two strings lexicographically (in dictionary order) in a case-sensitive manner. For case-insensitive comparison, use compareToIgnoreCase() method.

1. Strings in Lexicographic Order

If a string 'string1' comes before another string 'string2' in the dictionary, then string2 is said to be greater than 'string1' in string comparison.

  • string1 > string2‘string1’ comes AFTER ‘string2’ in dictionary.
  • string1 < string2‘string1’ comes BEFORE ‘string2’ in dictionary.
  • string1 = string2 ‘string1’ and ‘string2’ are equal.

2. String.compareTo() API

The compareTo() function takes one argument of type String. The second string is the String object itself, on which method is called. Note that compareTo() does the string comparison based on the Unicode value of each character in the strings.

int result = string1.compareTo(string2);

The result of this method is in integer value where –

  • positive integerstring1 lexicographically follows string2.
  • negative integerstring1 lexicographically preceds string2.
  • zero – both strings are equal.

3. Java Program to Compare Strings

The following Java program compares two strings case-sensitively using the compareTo() method. We ae using Hamcrest matches to assert the return values.

String name = "alex";

//same string
assertThat(name.compareTo("alex"), equalTo(0));

//Different cases
assertThat(name.compareTo("Alex"), greaterThan(0));
assertThat(name.compareTo("ALEX"), greaterThan(0));

//Different strings
assertThat(name.compareTo("alexa"), lessThan(0));
assertThat(name.compareTo("ale"), greaterThan(0));

4. Difference between compareTo() and equals()

The differences between compareTo() and equals() methods are:

  • The compare() compares lexicographically (dictionary ordering), and equals() checks for the content of both strings, although both methods are case-sensitive.
  • The return type of compareTo() is an integer type concluding that string that is greater than, less than or equal to another string. The return type of equals() is boolean, meaning the content of both strings is equal or not.

Happy Learning !!

Reference: String Java Doc

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode