The math.max() method in Java returns the maximum value among the specified arguments. Let’s deep dive into it.
math.max Java
Java math.max() is a built-in function that compares two numbers (int, float, double, or long type) and returns a maximum of those numbers. The math.max() function takes an int, double, float, and long and returns a maximum of two numbers.
Syntax
public static int max(int a, int b) public static double max(double a, double b) public static float max(float a, float b) public static long max(long a, long b)
Parameters
Two numbers out of which the maximum is to be determined.
Return Value
The maximum of the two arguments.
See the following figure.
Note
- If one argument is positive and the other is negative, the positive argument is returned.
- If both arguments are negative, then the one with the lower magnitude is returned.
- If one argument is positive zero, and the other argument is negative zero, then positive zero is returned. This is because the max() method considers negative zero to be smaller than positive zero (unlike numerical comparison operators).
- If either argument is NaN, then the final result is NaN.
Consider the following examples.
Example1.java: The following example demonstrates comparing two int, float, double, or long values.
See the following code.
public class Example1 { public static void main(String[] args) { int i1 = 2; int i2 = 3; float f1 = 2.0f; float f2 = 3.0f; double d1 = 2.0; double d2 = 3.0; long l1 = 2000000; long l2 = 3000000; System.out.println(Math.max(i1, i2)); System.out.println(Math.max(f1, f2)); System.out.println(Math.max(d1, d2)); System.out.println(Math.max(l1, l2)); } }
Output
->javac Example1.java ->java Example1 3 3.0 3.0 3000000
Example2.java: The following example demonstrates comparing a positive and a negative argument.
public class Example2 { public static void main(String[] args) { int a = 34; int b = -45; System.out.println(Math.max(a, b)); } }
Output
->javac Example2.java ->java Example2 34
Example3.java: The following example demonstrates comparing two negative arguments.
public class Example3 { public static void main(String[] args) { int a = -34; int b = -45; System.out.println(Math.max(a, b)); } }
Output
->javac Example3.java ->java Example3 -34
Example4.java: The following example demonstrates comparing positive zero and negative zero.
public class Example4 { public static void main(String[] args) { float a = -0.0f; float b = 0.0f; System.out.println(Math.max(a, b)); } }
Output
->javac Example4.java ->java Example4 0.0
Example5.java: The following example demonstrates a situation involving a NaN argument.
public class Example5 { public static void main(String[] args) { float a = 2f; System.out.println(Math.max(a, 2.0 % 0)); } }
Output
->javac Example5.java ->java Example5 NaN