Java Integer compareTo() Method
Example
Compare Integer objects:
public class Main {
public static void main(String[] args) {
Integer a = 5;
Integer b = 10;
System.out.println(a.compareTo(b));
System.out.println(b.compareTo(a));
System.out.println(a.compareTo(5));
}
}
Definition and Usage
The compareTo() method compares the value of an Integer object with the value of another Integer.
It returns 0 if the values are equal, a number less than 0 if this Integer is smaller, and a number greater than 0 if this Integer is larger. Java uses this method when it sorts a list of numbers.
Tip: To compare two int values, use the static compare() method.
Syntax
public int compareTo(Integer anotherInteger)
Parameter Values
| Parameter | Description |
|---|---|
| anotherInteger | Required. The Integer to compare with. |
Technical Details
| Returns: | An int: 0 if the values are equal, less than 0 if this Integer is smaller, and greater than 0 if it is larger. |
|---|
Related Pages
❮ Integer Methods