English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java other topics

Java Math max() usage and example

Java Math Mathematical Methods

The Java Math max() method returns the maximum value among the specified parameters.

The syntax of the max() method is:

Math.max(arg1, arg2)

Note:max() is a static method. Therefore, we can access this method using the Math class name.

max() parameter

  • arg1 / arg2 - Parameter for returning the maximum value

Note:The data types of each parameter should be int, long, float, or double.

max() return value

  • Returns the maximum value among the specified parameters

Example1:Java Math.max()

class Main {
  public static void main(String[] args) {
    //Math.max() with int parameter
    int num1 = 35;
    int num2 = 88;
    System.out.println(Math.max(num1, num2));  // 88
    //Math.max() with long parameter
    long num3 = 64532L;
    long num4 = 252324L;
    System.out.println(Math.max(num3, num4));  // 252324
    //Math.max() with float parameter
    float num5 = 4.5f;
    float num6 = 9.67f;
    System.out.println(Math.max(num5, num6));  // 9.67
    //Math.max() with double parameter
    double num7 = 23.44d;
    double num8 = 32.11d;
    System.out.println(Math.max(num7, num8));  // 32.11
  }
}

In the above example, we use the Math.max() method with int, long, float, and Double type parameters.

Example2:Get the maximum value from the array

class Main {
  public static void main(String[] args) {
    //Create an int type array
    int[] arr = {4, 2, 5, 3, 6;
    //Specify the first element of the array as the maximum value 'maximum value'
    int max = arr[0];
    for (int i = 1; i < arr.length; i++) {
            //Compare all elements with max
            //Assign the maximum value to max
      max = Math.max(max, arr[i]);
    }
    System.out.println("Maximum value: " + max);
  }
}

In the above example, we created an array named arr.Array. Initially, the variable max stores the first element of the array.

Here, we use a for loop to access all elements of the array. Note this 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.

Recommended Tutorials

Java Math Mathematical Methods