7.30.2014

Math: min() - Returns the smaller of two numbers

In order to return the smaller of two numbers, java.lang.Math class provides four static overloaded min() methods. The min() method takes two numbers as arguments and return the greater of the two.

The four overloaded min() methods are for int, long, float and double.

Some points about the min() method is given below:

  • If the two arguments are same, the method returns the same value.
  • The method always returns the value which is closer to the negative infinity or minimum value allowed for that data type.
  • For float and double, if one of the value is NaN, then the method returns NaN.
  • If one argument is positive zero and the other negative zero, the result is positive zero.
  • It is simple to nest multiple min() method.


Method Declaration:
public static int min(int a, int b)
public static long min(long a,long b)
public static float min(float a, float b)
public static double min(double a,double b)

Live Example:
import static java.lang.Double.NaN;

public class Demo {
    public static void main(String[] args) {
        System.out.println("Math.min(65, 20): " + Math.min(65, 20));
        System.out.println("Math.min(57L, 85L): " + Math.min(57L, 85L));
        System.out.println("Math.min(15.5F, 15.499F): " + Math.min(15.5F, 15.499F));
        System.out.println("Math.min(51.0, 51.01): " + Math.min(51.0, 51.01));
        System.out.println("Math.min(-0, +0): " + Math.min(-0, +0));
        System.out.println("Math.min(NaN, 45758345): " + Math.min(NaN, 45758345));
        System.out.println("Math.min(3, Math.min(7, 4)): " + Math.min(3, Math.min(7, 4)));
    }
}

Output:
Math.min(65, 20): 20
Math.min(57L, 85L): 57
Math.min(15.5F, 15.499F): 15.499
Math.min(51.0, 51.01): 51.0
Math.min(-0, +0): 0
Math.min(NaN, 45758345): NaN
Math.min(3, Math.min(7, 4)): 3

Use the social sharing button below to spread the knowledge among others.

0 comments:

Post a Comment