English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java String compareTo() method compares two strings in alphabetical order (alphabetical order). The comparison is based on the Unicode value of each character in the string.
The syntax of compareTo() method is:
string.compareTo(String str)
The compareTo() method takes a single parameter.
str - the string to be compared
if the strings are equal, thenreturns 0
if the string is located before the parameter str in alphabetical order, thenreturns a negative integer
if the string is located before the parameter str in alphabetical order, thenreturns a positive integer
class Main { public static void main(String[] args) { String str1 = "Learn Java"; String str2 = "Learn Java"; String str3 ="Learn Kolin"; int result; //compare str1and str2 result = str1.compareTo(str2); System.out.println(result); // 0 //compare str1and str3 result = str1.compareTo(str3); System.out.println(result); // -1 //compare str3and str1 result = str3.compareTo(str1); System.out.println(result); // 1 } }
Here,
str1and str2are equal. Therefore, str1.compareTo(str2) returns 0.
in alphabetical order, str1in str3before. Therefore, str1.compareTo(str3) returns a negative value, while str3.compareTo(str1) returns a positive value.
class Main { public static void main(String[] args) { String str1 ="Learn Python"; String str2 = "Learn Java"; //If str1and str2Equal, the result is 0 if (str1.compareTo(str2) == 0) { System.out.println("str1and str2Equal "); } else { System.out.println("str1and str2Not equal "); } } }
Output Result
str1and str2Not equal
The compareTo() method distinguishes between uppercase and lowercase letters (uppercase and lowercase).
class Main { public static void main(String[] args) { String str1 = "Learn Java"; String str2 = "learn Java"; int result; //compare str1and str2 result = str1.compareTo(str2); System.out.println(result); // -32 } }
When comparing "Learn Java" with "learn Java", we do not get 0. This is because compareTo() distinguishes between uppercase and lowercase letters.