Java Math class contains the methods required to do mathematical calculations. One of the very common calculations we need is finding the maximum of two numbers. For this task, java has introduced a java.lang.Math.max() method.
There are a few key things to know about the lang.Math.max() method. It is a static method, and therefore, you use it with the class name as Math.max. This Math.max() method can only take two arguments, so you can’t use it to find a Maximum number in a set with more than two numbers. It has four overloading methods for int, double, float, and long data types. Here are the method signatures of 4 methods.
public static int max(int a, int b)
public static double max(double a, double b)
public static long max(long a, long b)
public static float max(float a, float b)
Let’s use each one of these methods in our examples.
Finding the Maximum value of two integers.
public class Main {
public static void main(String args[])
{
int x = 40;
int y = 60;
System.out.println(Math.max(x, y));
}
}
The output will be 60.
Finding the maximum value between the two double values.
public class Main {
public static void main(String args[])
{
double x = 15.68;
double y = -37.47;
System.out.println(Math.max(x, y));
}
}
The output will be 15.68
Finding the maximum value between two floating-point numbers.
public class Main {
public static void main(String args[])
{
float x = -21.44f;
float y = -23.32f;
System.out.println(Math.max(x, y));
}
}
The output will be -21.44f
Finally, let’s find the maximum value between the two long values.
public class Main {
public static void main(String args[])
{
long x = 123456778;
long y = 453455633;
System.out.println(Math.max(x, y));
}
}
The output will be 453455633.
Although Math.max allows you to give two values, you can improvise it to find the maximum among three or more values. Check the following example.
public class Main
{
public static void main(String args[])
{
int x = 40;
int y = 60;
int z = 75;
//Find the maximum among three values using max() function
System.out.println(Math.max(z, Math.max(x,y)));
}
}
The output will be 75.
GO TO FULL VERSION