What is the Integer.compare method in Java?

compare is the static method of the Integer class and is used to compare two int values.

Syntax

public static int compare(int x, int y);

Return value

This method returns:

  • 0 if both values are the same.

  • A value less than zero , if the x < y.

  • A value greater than zero, if the x > y.

Integer.compare(x,y)

Case

Return value

x == y

0

x < y

< 0

x > y

> 0

Code

class IntegerCompare {
public static void main( String args[] ) {
int ten = 10;
int twenty = 20;
System.out.println("ten, ten : " + Integer.compare(ten, ten));
System.out.println("twenty, twenty : " + Integer.compare(twenty, twenty));
System.out.println("ten, twenty : " + Integer.compare(ten, twenty));
System.out.println("twenty, ten : " + Integer.compare(twenty, ten));
}
}

Explanation

In the code above:

  • We created two int variables:
ten = 10;
twenty = 20;
  • We used the compare method of the Integer class to compare the int values. First, we compared the same values:
compare(ten, ten);
compare(twenty, twenty);

The compare method returns 0 because both the compared values are the same.

  • Then, we compare ten with twenty:
compare(ten, twenty);

The compare method returns the value -1 because the first value is less than the second value.

  • Then, we compare twenty with ten:
compare(twenty, ten);

The compare method returns the value > 0 because the first value is greater than the second value.

Free Resources