In Java, comparing the records is needed when dealing with a large set of data. For instance, the comparison of values is much required while dealing with the encrypted or complex sort of records. The “compareTo()” method in Java does this comparison effectively by comparing the values of various data types as well as performing case insensitive comparison.
How to Use the “compareto()” Method in Java?
The Java “compareTo()” method compares two strings. It gives “0” if the string is equal to the compared string, less than “0” if the string is less (in terms of characters) than the compared string and greater than “0” if the string is greater (in terms of characters) than the compared string.
Syntax
public int compareTo(st)
public int compareTo(ob)
In these syntaxes, “st” and “ob” correspond to the string and object to be compared with the associated string, respectively.
Example 1: Applying the “compareTo()” Method to Compare the Strings and a String Object
This example applies the “compareTo()” method to compare the string with a string object and another string:
public class Compare {
public static void main(String args[]) {
String str1 = "Linuxhint";
String str2 = new String("Linuxhint");
String str3 = "Java";
System.out.println("Comparison -> "+str1.compareTo(str2));
System.out.println("Comparison -> "+str1.compareTo(str3));
}}
In this code:
- Initialize a string, a string object and another string, respectively.
- After that, apply the “compareTo()” method to compare the string and a string object.
- Lastly, apply the method again to compare both the initialized strings as well.
Output

This output indicates that the defined string and the string object are equal whereas it is not the case in the latter comparison.
Example 2: Applying the “compareTo()” Method to Compare the Strings by Ignoring the Case Sensitivity
In this demonstration, the discussed method will be applied to compare the strings in a case insensitive manner:
public class Compare {
public static void main(String args[]) {
String str1 = "JAVA";
String str2 = "java";
System.out.println("Comparison -> "+str1.compareTo(str2));
System.out.println("Comparison -> "+str1.compareToIgnoreCase(str2));
}}
In this block of code, initialize two same values with differences in their cases. After that, apply the “compareTo()” method twice to retrieve the case sensitive as well as case insensitive outcome, respectively.
Output

The latter comparison implies that both the case insensitive strings are evaluated as equal.
Conclusion
The Java “compareTo()” method compares the provided two strings. It gives 0, less than 0 and greater than 0 if the string is equal, less than and greater than the other string, respectively. This method can also be applied to perform the case insensitive comparison.