The compareTo() method of Integer class of java.lang package compares two Integer objects numerically and returns the value 0 if this Integer is equal to the argument Integer; a value less than 0 if this Integer is numerically less than the argument Integer; and a value greater than 0 if this Integer is numerically greater than the argument Integer (signed comparison).Â
Syntax :
public int compareTo(Integer anotherInt) Parameter : anotherInt- : the Integer to be compared. Return : - This method returns the value 0 if this Integer is equal to the argument Integer; - a value less than 0 if this Integer is numerically less than the argument Integer; - and a value greater than 0 if this Integer is numerically greater than the argument Integer (signed comparison).
Example 01 : To show working of java.lang.Integer.compareTo() method.Â
java
// Java program to demonstrate working// of java.lang.Integer.compareTo() methodimport java.lang.Integer;Â
class Gfg {Â
    // driver code    public static void main(String args[])    {        Integer a = new Integer(10);        Integer b = new Integer(20);Â
        // as 10 less than 20, Output will be a value less than zero        System.out.println(a.compareTo(b));Â
        Integer x = new Integer(30);        Integer y = new Integer(30);Â
        // as 30 equals 30, Output will be zero        System.out.println(x.compareTo(y));Â
        Integer w = new Integer(15);        Integer z = new Integer(8);Â
        // as 15 is greater than 8, Output will be a value greater than zero        System.out.println(w.compareTo(z));    }} |
Output:
-1 0 1
Example 02 :The working of compareTo() method in Java to compare two integer values.
Java
import java.io.*;Â
class GFG {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â Â Â Â Â Â Â Â Integer num1 = 10;Â Â Â Â Â Â Â Â Integer num2 = 5;Â Â Â Â Â Â Â Â Integer num3 = 10;Â Â Â Â Â Â Â Â int result1 = num1.compareTo(num2);Â Â Â Â Â Â Â Â int result2 = num1.compareTo(num3);Â Â Â Â Â Â Â Â int result3 = num2.compareTo(num3);Â Â Â Â Â Â Â Â System.out.println("Comparing num1 and num2: "Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â + result1);Â Â Â Â Â Â Â Â System.out.println("Comparing num1 and num3: "Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â + result2);Â Â Â Â Â Â Â Â System.out.println("Comparing num2 and num3: "Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â + result3);Â Â Â Â }} |
Output :
Comparing num1 and num2: 1 Comparing num1 and num3: 0 Comparing num2 and num3: -1
