Java - Math.min() Method



Description

The method gives the smaller of the two arguments. If the arguments have the same value, the result is that same value. If either value is NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero. If one argument is positive zero and the other is negative zero, the result is negative zero.The argument can be int, float, long, double.

Syntax

This method has the following variants −

public static double min(double arg1, double arg2)
public static float min(float arg1, float arg2)
public static int min(int arg1, int arg2)
public static long min(long arg1, long arg2)

Parameters

Here is the detail of parameters −

  • This method accepts any primitive data type as a parameter.

Return Value

  • This method returns the smaller of the two arguments.

Example 1

In this example, we're showing the usage of Math.min() method to get the minimum of two double values. We've created two double variables d1, d2 and initialized them with different values. Then using Math.min() method we're printing the minimum value of the given doubles.

public class Test { 
   public static void main(String args[]) {
      double d1 = 100.675;
      double d2 = 100.500;
     
      System.out.println(Math.min(d1,d2));	  
   }
}

This will produce the following result −

Output

100.5

Example 2

In this example, we're showing the usage of Math.min() method to get the minimum of two float values. We've created two float variables d1, d2 and initialized them with different values. Then using Math.min() method we're printing the minimum value of the given floats.

public class Test { 
   public static void main(String args[]) {
      float d1 = (float)100.675;
      float d2 = (float)100.500;
     
      System.out.println(Math.min(d1,d2));	  
   }
}

This will produce the following result −

Output

100.5

Example 3

In this example, we're showing the usage of Math.min() method to get the minimum of two int values. We've created two int variables d1, d2 and initialized them with different values. Then using Math.min() method we're printing the minimum value of the given ints.

public class Test { 
   public static void main(String args[]) {
      int d1 = 101;
      int d2 = 100;
      
      System.out.println(Math.min(d1,d2));	  
   }
}

This will produce the following result −

Output

100

Example 4

In this example, we're showing the usage of Math.min() method to get the minimum of two int values. We've created two int variables d1, d2 and initialized them with different values. Then using Math.min() method we're printing the minimum value of the given ints.

public class Test { 
   public static void main(String args[]) {
      long d1 = 101L;
      long d2 = 100L;
     
      System.out.println(Math.min(d1,d2));	  
   }
}

This will produce the following result −

Output

100
java_numbers.htm
Advertisements