Java Integer compareTo() method

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 20-Sep-2019 11:04:07
Advertisements