compare
is the static method of the Integer
class and is used to compare two int
values.
public static int compare(int x, int y);
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
.
Case | Return value |
x == y | 0 |
x < y | < 0 |
x > y | > 0 |
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));}}
In the code above:
int
variables:ten = 10;
twenty = 20;
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.
ten
with twenty
:compare(ten, twenty);
The compare
method returns the value -1
because the first value is less than the second value.
twenty
with ten
:compare(twenty, ten);
The compare
method returns the value > 0
because the first value is greater than the second value.