Math.max()
Returns the larger of two numbers.
Available since: Java 1.0
Syntax
static int max(int a, int b)Parameters
| Parameter | Type | Description |
|---|---|---|
| a | int, long, float, double | The first number. |
| b | same type as a | The second number of the same type. |
Return value
same type as aThe larger of the two values.
Examples
The larger of two and of three numbers:
void main() {
IO.println(Math.max(7, 12));
IO.println(Math.max(Math.max(4, 9), 2));
}Output:
12
9The maximum of an array — in a loop or with a stream:
void main() {
int[] scores = {72, 95, 88};
int best = Integer.MIN_VALUE;
for (int s : scores) {
best = Math.max(best, s);
}
IO.println(best);
IO.println(Arrays.stream(scores).max().getAsInt());
}Output:
95
95Notes
The method takes exactly two arguments. For collections there is Collections.max(), for streams max(). If you mix int and double, the result is a double: Math.max(3, 2.5) returns 3.0.
See also
- Math.min() — Returns the smaller of two numbers.
- Math.abs() — Returns the absolute value of a number — the value without a minus sign.
- Arrays.stream() — Creates a stream from an array — for sums, filters and transformations.
Related recipes
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.