Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Integer.compare()

Compares two int values: negative means x is smaller, 0 means equal, positive means x is larger.

Available since: Java 7

Syntax

public static int compare(int x, int y)

Parameters

ParameterTypeDescription
xintThe first number.
yintThe second number.

Return value

int-1, 0 or 1.

Examples

The three possible results:

void main() {
    IO.println(Integer.compare(3, 7));
    IO.println(Integer.compare(7, 3));
    IO.println(Integer.compare(5, 5));
}

Output:

-1
1
0

A comparator for sorting by age:

record Person(String name, int age) {}
 
void main() {
    List<Person> people = new ArrayList<>(List.of(
        new Person("Anna", 30), new Person("Oleg", 25), new Person("Mia", 41)));
 
    people.sort((a, b) -> Integer.compare(a.age(), b.age()));
    IO.println(people);
}

Output:

[Person[name=Oleg, age=25], Person[name=Anna, age=30], Person[name=Mia, age=41]]

Why not a - b: subtraction overflows and gives the wrong sign:

void main() {
    int a = Integer.MIN_VALUE;
    int b = 1;
    IO.println(a - b);
    IO.println(Integer.compare(a, b));
}

Output:

2147483647
-1

Notes

Long, Double, Short, Byte and Character have the same methods. Double.compare() handles NaN and -0.0 correctly, which the < and > operators do not. For sorting objects Comparator.comparingInt(Person::age) is shorter.

See also

In the tutorial

  • Wrapper classes — Integer, Double, Boolean and Character in Java: autoboxing and unboxing, null instead of a number, the Integer cache and why wrappers must not be compared with ==.

Thanks for reading!

Donate to the site — we work hard for you.