Java Math max() Method with Examples

Getting the maximum of two given numbers (Java Math max method)

Now let’s have a look at another method max, with which we can get the greatest of the two given values. The values can be integers, long, double, or float values. So, this max method is also overloaded. Let’s see all the methods one by one.

The below program demonstrates the max method with integer arguments. This returns the greatest integer of the given two arguments. This is like we are asking – “Hey max, take these two integers and tell me which one is greater”. Let’s try to implement this program –

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

When it comes to returning values, we can store these values in some variables. So if you ever need to store the greater value for future use in the program, you can store it in a variable. Now let’s see how can we do the same thing with other types of data, like long, double, and float.

import java.lang.Math;
public class UnderstandingMath {
public static void main(String[] args) {
System.out.println(Math.max(56.908f, 56.909f));
}
}

This method returns the greater floating-point value, which is 56.909. Have a look at another program for double data this time –

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

The output of the above program comes out to be 19.987881778165, which was desired, The below program works for a long data.

import java.lang.Math;
public class UnderstandingMath {
public static void main(String[] args) {
System.out.println(Math.max(1872783928748L, 347839287492834L));
}
}

The output of the above program comes out to be 347839287492834. So, these are some variants of the max method, which returns the greater value among the two given values.

Special cases-

  • If both arguments are the same values, the output is the same value.
  • If any one value is NaN, the output is also NaN.
  • For this method, the negative zero is considered less than the positive zero. So if the two arguments are negative zero and positive zero, then the output is positive zero.