Math.max() Method in Java

Math.max() Method in Java | In Java to find the max of two numbers, we can use the max() method which is defined in the java.lang.Math class. There are several overloaded forms of the max() method and all of them return the greater of two arguments.

The overloaded forms of Math.max() methods are,

  • 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)

The max() method is implemented like,

public static int max(int a, int b) {
   return (a >= b) ? a : b;
}

Math.max() Examples in Java

public class Test {
   public static void main(String[] args) {
      System.out.println(Math.max(10, 20)); 
      System.out.println(Math.max(15, 15)); 
      System.out.println(Math.max(25, 15)); 
   }
}

Output:-

20
15
25

If we import the Math class statically and then we can invoke the max() method without calling through its class name.

import static java.lang.Math.*;
public class Test {
   public static void main(String[] args) {
      System.out.println(max(10, 20)); // 20
   }
}

The “import static java.lang.Math.*;” statement will import all static members of the Math class. But if we want to import only the max() method of the Math class, not another static method and variables of the Math class then we can use the “import static java.lang.Math.max;” statement. Learn more about static import in Java

import static java.lang.Math.max;
public class Test {
   public static void main(String[] args) {
      System.out.println(max(10, 20));
   }
}

Special Cases of Java Math.max()

1) If the arguments have the same value, the result is the same value.

System.out.println(Math.max(10, 10));

Output:- 10

2) If either value is NaN, then the result is NaN.

import static java.lang.Math.max;
public class Test {
   public static void main(String[] args) {
      System.out.println(Math.max(Double.NaN, 20));
      System.out.println(Math.max(10, Double.NaN));
      System.out.println(Math.max(Double.NaN, Double.NaN));
   }
}

Output:-

NaN
NaN
NaN

3) 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 negative zero, the result is positive zero.

public class Test {
   public static void main(String[] args) {
      System.out.println(Math.max(0, -0));
      System.out.println(Math.max(-0, 0));
   }
}

Output:-

0
0

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *