The compareTo() method compares two strings lexicographically (in the dictionary order). The comparison is based on the Unicode value of each character in the strings.
Example
Syntax of compareTo()
The syntax of the compareTo() method is:
string.compareTo(String str)
Here, string is an object of the String class.
compareTo() Parameters
The compareTo() method takes a single parameter.
- str - the string to be compared
compareTo() Return Value
- returns 0 if the strings are equal
- returns a negative integer if the
stringcomes before thestrargument in the dictionary order - returns a positive integer if the
stringcomes after thestrargument in the dictionary order
Example: Java String compareTo()
Here,
- str1 and str2 are equal. Hence,
str1.compareTo(str2)returns 0. - str1 comes before str3 in the dictionary order. Hence,
str1.compareTo(str3)returns negative, andstr3.compareTo(str1)returns positive.
Example 2: Check if Two Strings are Equal
Output
str1 and str2 are not equal
Example 3: compareTo() With Case
The compareTo() method takes the letter case (uppercase and lowercase) into consideration.
When "Learn Java" is compared to "learn Java", we do not get 0. It is because compareTo() takes the letter case into consideration.
Notes:
- If you need to compare two strings ignoring case differences, use the Java String compareToIgnoreCase() method.
- If you pass
nullto thecompareTo()method, you will get an error.
Related Tutorial: Java String equals()