Java.lang Package Classes

Java Integer - compareTo() Method



The java.lang.Integer.compareTo() method is used to compare two Integer objects numerically.

Syntax

public int compareTo(Integer anotherInteger)

Parameters

anotherInteger Specify the Integer to be compared.

Return Value

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).

Exception

NA.

Example:

In the example below, the java.lang.Integer.compareTo() method is used to compare given Integer objects.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating Integer objects
    Integer val1 = 5;
    Integer val2 = 5;
    Integer val3 = -5;

    //comparing Integer objects 
    System.out.println("comparing val1 with val2: " + val1.compareTo(val2)); 
    System.out.println("comparing val1 with val3: " + val1.compareTo(val3)); 
    System.out.println("comparing val3 with val1: " + val3.compareTo(val1));    
  }
}

The output of the above code will be:

comparing val1 with val2: 0
comparing val1 with val3: 1
comparing val3 with val1: -1

❮ Java.lang - Integer

5