Java Math min()

The min() method returns the smaller value among the specified arguments.

Example

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

// returns minimum of 25 and 31 System.out.println(Math.min(25, 31));
} } // Output: 25

Syntax of Math.min()

The syntax of the min() method is:

Math.min(arg1, arg2)

Here, min() is a static method. Hence, we are accessing the method using the class name, Math.


min() Parameters

The min() method takes two parameters.

  • arg1/arg2 - arguments among which smaller value is returned

Note: The data types of the arguments should be either int, long, float, or double.


min() Return Value

  • returns the minimum value among the specified arguments

Example 1: Java Math.min()

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

    // Math.min() with int arguments
    int num1 = 35;
    int num2 = 88;
System.out.println(Math.min(num1, num2)); // 35
// Math.min() with long arguments long num3 = 64532L; long num4 = 252324L;
System.out.println(Math.min(num3, num4)); // 64532
// Math.min() with float arguments float num5 = 4.5f; float num6 = 9.67f;
System.out.println(Math.min(num5, num6)); // 4.5
// Math.min() with double arguments double num7 = 23.44d; double num8 = 32.11d;
System.out.println(Math.min(num7, num8)); // 23.44
} }

In the above example, we have used the Math.min() method with int, long, float, and double type arguments.


Example 2: Get a minimum 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 minimum value
    int min = arr[0];

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

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

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

Here, we have used the for loop to access all elements of the array. Notice the 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.


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