Find the maximum of numbers with Math.max in Java
In this example, we shall show you how to find the maximum numbers in Java, using the Math Class and the method Math.max.
1. About Math Class
java.lang.Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
By using the associated functions directly, you can skip creating the logic of all the functions. Every mathematical operation/function is in one way or the other part of the Math Class. Few of the examples include
log10() and many others.
Among all the mentioned above methods, one such method is max(). Let us read more to understand what it does.
2. Math.max method in Java
Math.max() is used to find out the largest of two numbers. It takes two parameters and returns the larger of the two. The data type of the returning variable is the same as the input parameters.
max(double a, double b),
max(float a, float b),
max(int a, int b),
max(long a, long b) API methods of Math according to the types of arguments to get the greater of the two values, as described in the code snippet below.
3. Math.max examples in Java
In the first example below, we will be demonstrating the usage of
Math.max() with different data types.
50 56.8 23.15 9876
In the second example below, we will be using
Math.max()with positive and negative values.
50 -10 50
This was an example of how to find the maximum numbers in Java, using the Math class and the method
5. Download the Source Code
You can download the code used in the examples above.
You can download the full source code of this example here: Find the maximum of numbers with Math.max in Java
Updated on Sept. 30th, 2020