The max() method returns the maximum value among the specified arguments.
Example
Syntax of Math.max()
The syntax of the max() method is:
Math.max(arg1, arg2)
Here, max() is a static method. Hence, we are accessing the method using the class name, Math.
max() Parameters
The max() method takes two parameters.
- arg1/arg2 - arguments among which maximum value is returned
Note: The data types of the arguments should be either int, long, float, or double.
max() Return Value
- returns the maximum value among the specified arguments
Example 1: Java Math.max()
In the above example, we have used the Math.max() method with int, long, float, and double type arguments.
Example 2: Get a maximum value from an array
In the above example, we have created an array named arr. Initially, the variable max stores the first element of the array.
Here, we have used the for loop to access all elements of the array. Notice the line,
max = Math.max(max, arr[i])
The Math.max() method compares the variable max with all elements of the array and assigns the maximum value to max.