7.30.2014

Math: max() - Returns the greater of two numbers

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

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

Some points about the max() 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 positive infinity or maximum 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 max() method.


Method Declaration:
public static int max(int a, int b)
public static long max(long a,long b)
public static float max(float a, float b)
public static double max(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.max(65, 20): " + Math.max(65, 20));
        System.out.println("Math.max(57L, 85L): " + Math.max(57L, 85L));
        System.out.println("Math.max(15.5F, 15.499F): " + Math.max(15.5F, 15.499F));
        System.out.println("Math.max(51.0, 51.01): " + Math.max(51.0, 51.01));
        System.out.println("Math.max(-0, +0): " + Math.max(-0, +0));
        System.out.println("Math.max(NaN, 45758345): " + Math.max(NaN, 45758345));
        System.out.println("Math.max(3, Math.max(7, 4)): " + Math.max(3, Math.max(7, 4)));
    }
}

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

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

0 comments:

Post a Comment