Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

JAVA Comparable Interface

It is an interface present in java.lang package.
It contains only one method that is compareTo().

The general form of this method is:

obj1.compareTo(obj2);

  • • this method returning three values that is any +ve value, any -ve value, or 0.
  • • When obj1 is coming before obj2, then compareTo() returns -ve value.
  • • When obj1 is coming after obj2, then compareTo() returns +ve value.
  • • When obj1 and obj2 are equal, then compareTo() returns 0.
  • • When obj1 is comparing with null, then compareTo() returns NullPointerException.

Let's see a demo program of compareTo() method:

ComparableDemo.java
import java.util.*;
class ComparableDemo
{
	public static void main(String args[])
	{
		System.out.println("A".compareTo("Z"));
		System.out.println("Z".compareTo("B"));
		System.out.println("A".compareTo("A"));
		System.out.println("A".compareTo(null));
	}
}
Output

-25
24
0
Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.compareTo(String.java:1196)
at ComparableDemo.main(ComparableDemo.java:9)



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext