Java Integer compareTo() method


The java.lang.Integer.compareTo() method compares two Integer objects numerically. 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.

At first, set two Integer objects −

Integer obj1 = new Integer("100");
Integer obj2 = new Integer("200");

Now, compare those object −

int res = obj1.compareTo(obj2);

Following is an example to implement the compareTo() method in Java −

Example

public class Main {
   public static void main(String[] args) {
      Integer obj1 = new Integer("100");
      Integer obj2 = new Integer("200");
      int res = obj1.compareTo(obj2);
      if(retval > 0) {
         System.out.println("obj1 is greater than obj2");
      } else if(retval < 0) {
         System.out.println("obj1 is less than obj2");
      } else {
         System.out.println("obj1 is equal to obj2");
      }
   }
}

Output

obj1 is less than obj2

Updated on: 20-Sep-2019

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements