1. Comparable interface is available in java.lang package.
  2. This interface contains only one method compareTo()

public int compareTo(Object obj)

  1. returns –ve number if obj1 has to come before obj2.
  2. returns + ve number if obj1 has to come after obj2.
  3. returns 0 if obj1 and obj2 are equal(Duplicate Objects).


class CompareToDemo{
    public static void main(String args[])
System.out.println("A".compareTo("Z"));// -ve
System.out.println("K".compareTo("A")); //-ve
System.out.println("K".compareTo("K")); // 0
System.out.println("a".compareTo("A"));// +ve
System.out.println("A".compareTo(new Integer(10)));// ClassCastException
System.out.println("A".compareTo(null)); // NullPointerException

while Inserting the objects into the TreeSet JVM internally uses compareTo() method if we are depending on natural sorting order.

Sometimes we have to define our own customized sorting order, then we should go for comparator Interface.