compareTo() - String Methods in Java


This article is a part of String Methods in Java.
This method compares two strings lexicographically. The comparison is based on the Unicode value of each character present in the string. The parameter passed in this method is of String type.


Return type

The return type of compareTo() method is int. It returns 0 if the two strings are equal. A negative value is returned if the string is less than the other string, and a value greater than 0 is returned if the string is greater than the other string.
Let us look at an example code to understand this method.

Example


Output

Let us look at the output of the above example code.

String Methods compareTo()
Fig.1- String Method - compareTo()

In the first scenario, the string “LearningJournal” is greater than the string “Learningjournal,” it returns -32. In the second case, the strings are equal, so the value returned is 0.
Let us look at another case in relation to compareTo() method.

compareToIgnoreCase()

This method compares two strings lexicographically, ignoring lower and upper case differences. The parameter passed in this method is of String type.

Return type

The return type of compareToIgnoreCase() method is int. It returns 0 if the two strings are equal, ignoring the upper and lower case differences. A negative value is returned if the string is less than the other string, and a value greater than 0 is returned if the string is greater than the other string.
Let us look at an example code to understand this method.

Example


Output

Let us look at the output of the above example code.

String Methods compareToIgnoreCase()
Fig.2- String Method - compareToIgnoreCase()

Since case is not a concern in this method all the three strings are equal.

Read More

Author : Satyam Kumar -



You will also like: