Java Math max() Method
The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type.
Syntax:
- public static double max(double a, double b)
- public static float max(float a, float b)
- public static int max(int a, int b)
- public static long max(long a, long b)
Parameters:
The parameters ‘a’ and ‘b’ represent the two values.
Return Value:
The max() method returns the larger of a and b.
- It returns the result of same value, is the arguments have same value
- It returns NaN, if either value is NaN.
- It returns positive zero, if one argument is positive zero and the other is negative zero.
Example 1:
public class JavaMathMaxExample1 {
public static void main(String[] args) {
double a = 20;
double b=134;
//returns the greater of two numbers
System.out.println("The greater number between "+a+" and "+ b+ " is
:
"+Math.max(a,b));
}
}
Output:
The greater number between 20.0 and 134.0 is : 134.0
Example 2:
public class JavaMathMaxExample2 {
public static void main(String[] args) {
int a = 20;
int b= Integer.MAX_VALUE;
//returns the greater of two numbers
System.out.println("The greater number between "+a+" and "+ b+ "
is : "+Math.max(a,b));
}
}
Output:
The greater number between 20 and 2147483647 is : 2147483647
Example 3:
public class JavaMathMaxExample3 {
public static void main(String[] args) {
Double a = 20.9d;
Double b=Double.NaN;
//returns NaN, if either value is NaN
System.out.println("The greater number between "+a+" and "+ b+ "
is : "+Math.max(a,b));
}
}
Output:
The greater number between 20.9 and NaN is : NaN
Example 4:
public class JavaMathMaxExample4 {
public static void main(String[] args) {
float a = 0f;
float b=-0f;
//returns positive zero, if one argument is positive zero and the
other is negative zero
System.out.println("The greater number between "+a+" and "+ b+ "
is : "+Math.max(a,b));
}
}
Output:
The greater number between 0.0 and -0.0 is : 0.0
Example 5:
public class JavaMathMaxExample5 {
public static void main(String[] args) {
float a =Float.MIN_VALUE ;
double b=Double.MIN_VALUE;
System.out.println("The greater number between "+a+" and "+ b+ "
is : "+Math.max(a,b));
}
}
Output:
The greater number between 1.4E-45 and 4.9E-324 is : 1.401298464324817E-45
