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)/O)

Java Reader/Writer

Java Other Topics

Java Math min() usage and example

Java Math Mathematical Methods

The Java Math min() method returns the smallest value among the specified parameters.

The syntax of the min() method is:

Math.min(arg1, arg2)

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

min() parameter

  • arg1 / arg2 - Parameter for returning the minimum value

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

min() return value

  • Returns the minimum value among the specified parameters

Example1:Java Math.min()

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

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

Example2:Get the minimum value from the array

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

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

Here, we use a for loop to access all elements of the array. Note this line,

min = Math.min(min, arr[i])

The Math.min() method compares the variable min with all elements of the array and assigns the minimum value to min.

Recommended Tutorials

Java Math Mathematical Methods