CKTIS / Java
Integer.max(): the larger of two int values
`Integer.max(a, b)` compares two signed `int` values and returns the larger one as an `int`. If both inputs are equal, it returns their common value.
Version: Java SE 21
Syntax
public static int max(int a, int b)
int larger = Integer.max(a, b);Integer.max() is shorthand for the method Integer.max(int, int), not a zero-argument call. It is a static method on java.lang.Integer: call it as Integer.max(a, b). No object or explicit import is needed. The method has been available since Java 8 and is part of Java SE 21.
The parameters and return value have the primitive type int. The method returns the larger value in signed numeric order, so -3 is larger than -8. If the values are equal, it returns their common value. It gives the same result as Math.max(int, int), whereas Integer.MAX_VALUE is a constant representing the largest possible int.
If you pass a variable of type Integer, Java automatically unboxes it to int. If that variable holds null, unboxing throws a NullPointerException before the method runs.
Examples
public class Main {
public static void main(String[] args) {
int larger = Integer.max(12, 7);
System.out.println(larger);
System.out.println(Integer.max(-8, -3));
System.out.println(Integer.max(5, 5));
}
}
Result
12 -3 5
The three lines show the larger of two positive values (`12`), the larger of two negative values (`-3`), and the result for equal arguments (`5`), in that order.
Related lessons
- Java · Lesson 66 · Basic · Version: 2