Java String CompareTo() Method

How to compare strings in Java?

You can compare strings in Java using the compareTo() method. It accepts two parameters and compare them lexicographically.

What is the difference between the compareTo() method and the equals() method in Java?

equals() method compareTo() method
Used to check if two objects are exactly the same. Used to compare two objects and determine their relative order.

Returns a boolean:

  • true if the objects are considered equal.
  • false otherwise.

Returns an integer:

  • Negative value if the first object is considered “less than” the second.
  • Zero if the objects are considered equal.
  • Positive value if the first object is considered “greater than” the second.

What does compareTo () return in Java?

compareTo() method in Java returns an integer. It can have three possible values:

  • Negative value: When the first object is considered “less than” the second.
  • Zero: When the objects are considered equal.
  • Positive value: When the first object is considered “greater than” the second.


Java String compareTo() Method with Examples

Strings in Java are objects that are supported internally by an array only which means contiguous allocation of memory for characters .  Please note that strings are immutable in Java which means once we create a String object and assign some values to it, we cannot change the content. However we can create another String object with the modifications that we want.

The String class of Java comprises a lot of methods to execute various operations on strings and we will be focusing on the Java String compareTo() method in this article.

Similar Reads

Java String.compareTo() Method

The Java compareTo() method compares the given string with the current string lexicographically. It returns a positive number, a negative number, or 0. It compares strings based on the Unicode value of each character in the strings....

Syntax

...

Variants of CompareTo() Method

int comparison = str1.compareTo(str2);...

Exceptions in Java String compareTo() Method

There are three variants of the compareTo() method which are as follows:...

Conclusion

...

Java String CompareTo() Method- FAQs

...