Using compareTo Method in Java

The compareTo() method is part of the Comparable interface in Java. It aids in comparing the current object to a specified one, enabling custom class objects to be sorted. When you adopt the Comparable interface, it's essential to provide an implementation for the compareTo() method. The method will yield a negative value, zero, or a positive value, depending on whether the present object is deemed less than, equivalent to, or greater than the other object. When comparing strings, lexicographical comparison is employed by compareTo(). Several foundational classes, such as String, Integer, and Date, are equipped with a Comparable interface, ensuring they follow a natural order. In this Java CompareTo Example, two strings are established and compared through the compareTo() method. Click Execute to run the Java CompareTo Example online and see the result.
Using compareTo Method in Java Execute
public class CompareToDemo {
    public static void main(String[] args) {
        String str1 = "apple";
        String str2 = "banana";
        String str3 = "apple";

        System.out.println(str1.compareTo(str2));
        System.out.println(str1.compareTo(str3));
    }
}
Updated: Viewed: 42 times