What is the Integer.compareTo method in Java?
The compareTo() method of the Integer class compares the current object’s Integer value to another object’s Integer value.
Syntax
public int compareTo(Integer b);
Parameter
b: An object of typeIntegerwhose value is compared to the caller object’sIntegervalue.
Return value
This method returns:
-
0if the caller object’s value and the passed argument’s value are the same. -
A positive value if the caller object’s value is greater than the argument’s value.
-
A negative value if the caller object’s value is less than the argument’s value.
Code
The code below uses the compareTo method to compare the Integer values as follows:
class IntegerCompareToExample {public static void main( String args[] ) {Integer val1 = 10;Integer val2 = 10;System.out.println("10, 10 : " + val1.compareTo(val2));val2 = 11;System.out.println("10, 11 : " + val1.compareTo(val2));val2 = 9;System.out.println("10, 9 : " + val1.compareTo(val2));}}
Explanation
In the code above:
-
In line 3 we create an
Integerobject variable with the nameval1and the value10. -
In lines 5 and 6 we create another
Integervalueval2with the value10. We call thecompareTomethod on theval1object withval2as the argument. We get0as a result because both the values are equal. -
In lines 8 and 9 we change the value of
val2to11and call thecompareTomethod on theval1object withval2as the argument. We get-1as a result becauseval1is less thanval2. -
In lines 11 and 12 we change the value of
val2to9and call thecompareTomethod on theval1object withval2as the argument. We get1as a result becauseval1is greater thanval2.