Find Maximum of Two Numbers max()

java.lang.Math class comes with many methods to do simple basic numeric operations. One such one is max() method which returns the maximum of two numbers passed as parameters.

One advantage of Math class methods is that they are declared as static so that they can be called without the need of object creation.

Following is the Math class signature as defined in java.lang package.

public final class Math extends Object

max() method in Math class is 4 times overloaded accepting 4 different types of arguments.

  1. int max(int a, int b): Returns maximum of two integer values passed as parameter.
  2. long max(long a, long b): Returns maximum of two long values passed as parameter.
  3. float max(float a, float b): Returns maximum of two float values passed as parameter.
  4. double max(double a, double b): Returns maximum of two double values passed as parameter.

Observe, the above methods data type of the returned value is the same as parameters.

Following example on "Find Maximum of Two Numbers max()" illustrates the above four methods.
public class MathFunctionDemo
  public static void main(String args[])
   int a = 25, b = 50;			//  two integer values
   long c = 50, d = 20;                 // two long values
   float e = 25.5f, f = 10.4f;		//  two float values
   double g = 20.3, h = 50.2;		//  two double values

   System.out.println("Maximum of integer values 25 and 50 is " + Math.max(a, b));     
   System.out.println("Maximum of long values 50 and 20 is " + Math.max(c, d));     
   System.out.println("Maximum of float values 25.5 and 10.4 is " + Math.max(e, f));     
   System.out.println("Maximum of double values 20.3 and 50.2 is " + Math.max(g, h));     

Maximum max()
Output screenshot of Find Maximum of Two Numbers max()

Leave a Comment

Your email address will not be published.