Java Math max()

The max() method returns the maximum value among the specified arguments.

Example

class Main {
  public static void main(String[] args) {

// compute max of 88 and 98 System.out.println(Math.max(88, 98));
} } // Output: 98

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()

class Main {
  public static void main(String[] args) {

    // Math.max() with int arguments
    int num1 = 35;
    int num2 = 88;
    System.out.println(Math.max(num1, num2));  // 88

    // Math.max() with long arguments
    long num3 = 64532L;
    long num4 = 252324L;
    System.out.println(Math.max(num3, num4));  // 252324

    // Math.max() with float arguments
    float num5 = 4.5f;
    float num6 = 9.67f;
    System.out.println(Math.max(num5, num6));  // 9.67

    // Math.max() with double arguments
    double num7 = 23.44d;
    double num8 = 32.11d;
    System.out.println(Math.max(num7, num8));  // 32.11
  }
}

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

class Main {
  public static void main(String[] args) {

    // create an array of int type
    int[] arr = {4, 2, 5, 3, 6};

    // assign first element of array as maximum value
    int max = arr[0];

    for (int i = 1; i < arr.length; i++) {

// compare all elements with max // assign maximum value to max max = Math.max(max, arr[i]);
} System.out.println("Maximum Value: " + max); } }

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.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges