The Math.max() is a built-in method for finding the greatest value from two numbers. It is a static method and is called directly using the Math class of java.lang package. The Math.max() method returns a numeric output. There are no specific exceptions thrown by this method. However, the compile-time exceptions can be thrown due to invalid datatype conversions or incorrect input provided. Below is the visual representation of the Math.max():
This article provides a practical demonstration of the max() function in Java.
How to Use the Math.max() Function in Java?
In Java, the Math.max() function accepts two numbers as arguments, performs comparison, and retrieves the maximum number.
Syntax
The syntax of the Math.max() method is given as follows:
public static datatype Math.max(datatype value1, datatype value2 )
where,
- The “datatype” can be long, double, float, or int. The output returned will be also from the mentioned datatypes respectively.
- The “value1” and “value2” are the arguments for this syntax.
The table given below discusses the return type of the output of the Math.max() function:
Argument 1 | Argument 2 | Return Type |
---|---|---|
Integer | Integer | Integer/ Long/ Float/ Double |
Integer | Double | Double |
Integer | Float | Double/ Float |
Integer | Long | Double/ Long/ Float |
Double | Double | Double |
Double | Float | Double |
Double | Long | Double |
Float | Float | Double/Float |
Float | Long | Double/Float |
Long | Long | Long/Float/Double |
Note: If the arguments provided to the Math.max() method are of different datatypes then the datatype of the variable to store the results of the Math.max() function must be the same as the above-mentioned returned type.
Let’s explore various examples of using the Math.max() method in Java.
Example 1: Find the Maximum of Two Integers Using the Math.max()
The example given below determines the maximum of two integer values. The print statements display the output of the max() function that takes “3” and “4” as integer parameters in the code given below:
public class FindMaxValue {
public static void main(String[] args) {
System.out.println("The maximum value is " + Math.max(3, 4));
}
}
Note: The user can also provide long values for the method.
Output
Example 2: Find the Maximum of Two Float Values Using the Math.max() Function
In the following code, the Math.max() is used to calculate the maximum of the given float values:
public class FindMaxValue {
public static void main(String[] args) {
System.out.println("The maximum of two float value is " + Math.max(3.5,4.5));
}
}
Output
Example 3: Find the Maximum of Two Negative Numbers Using the Math.max()
The example given below determines the greatest value among the two negative numbers and displays the output:
public class FindMaxValue {
public static void main(String[] args) {
System.out.println("The maximum of two negative values is " + Math.max(-2,-1));
}
}
Output
Example 4: Find the Maxmium of a Positive and Negative Value Using the Math.max() Function
The Math.max() method is called directly within the print statement to calculate the highest value of two given numeric values as shown in this example:
public class FindMaxValue {
public static void main(String[] args) {
System.out.println("The maximum of two negative values is " + Math.max(2,-1));
}
}
Output
Example 6: Find the Maximum Value in an Array by Using the Math.max() Method
In Java, arrays are the collection of related data. The example given below demonstrates the functionality of the Math.max() method with an integer array:
public class FindMaxValue {
public static void main(String[] args) {
int[] numArray= {5,6,4,2,3,7,1,9};
int Maximum=numArray[0];
for (int i=0;i<numArray.length;i++) {
Maximum=Math.max(Maximum, numArray[i]);
}
System.out.println("The maximum value in the array is " + Maximum);
}
}
Here,
- An array named “numArray” is declared and initialized with integer values inside the main() method.
- The integer variable “Maximum” is initialized with the value of the first element in the “numArray” array, i.e., 5.
- A for loop iterates over each index of the array. The integer “i” is initialized with the 0 value and is increment by 1 in each iteration.
- The loop compares the value of the “Maximum” integer and the array’s value at index “i” by using the Math.max() method. The maximum of the two values is kept in the “Maximum” variable. When the loop terminates, the print statement displays the maximum value.
Output
Example 7: Find the Maximum of Three Numbers Using the User Input in the Math.max() Method
The Math.max() method accepts only two parameters. However, we can use this method to find the maximum of three values by using the nested max(). In this process, the Math.max() is called inside another Math.max() method. The output returned by the inner max() method is provided as input to the outer max() method. The code is given as follows:
import java.util.*;
public class FindMaxValue {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter three integers");
int firstInteger=input.nextInt();
int secondInteger=input.nextInt();
int thirdInteger=input.nextInt();
System.out.println("The Maximum value is " + Math.max(firstInteger, Math.max(secondInteger, thirdInteger)));
}
}
In the code given above:
- The Scanner class is imported and used to accept the input via the keyboard.
- A print statement prompts the user to enter three integer-type values. The input is stored in the three integer variables i.e., “firstInteger”, “secondInteger” and “thirdIntger”.
- The nested max() method is called inside the print statement. The inner max() calculates the maximum of “secondInteger” and “thirdInteger”. The value retrieved by the stated method will be then compared with the “firstInteger” to find the maximum value.
Output
Example 8: Find Maximum of Four Integers Using the Math.max() Function
The Math.max() method can also be used to find the maximum value between four numeric values as shown below:
import java.util.*;
public class FindMaxValue {
public static void main(String[] args) {
System.out.println("The Maximum value is " + Math.max(Math.max(8, 9), Math.max(2,-1.5)));
}
}
Within the above-mentioned code:
- The nested max() is used inside the print statement. The inner Math.max() methods will return a value i.e., 9 and 2.0. These two values will be then tested for maximum value using the outer Math.max() call. The output will be displayed using the print statement.
Output
Example 9: Find the Maximum Value of an Expression Using the Math.max() Function
The Math.max() method determines the maximum value after calculating an expression as shown in the example below:
public class FindMaxValue {
public static void main(String[] args) {
int number1 = 25;
int number2 = 98;
System.out.println("The maximum value is " + Math.max(number1 * 2,number2 + 3));
}
}
Here, in this code,
- The two integer variables “number1” and “number2” are declared and initialized with respective values within the main() method.
- First, the specified expression is calculated and then the maximum of the two numbers is determined using the Math.max() inside the print statement.
Output
What are the Exceptions of Math.max() Function in Java?
The two most common exceptions that are thrown in the Math.max() method are the “Type mismatch” and “Method Not Applicable” Exception. They are discussed as follows:
Exception 1: TypeMismatch Exception
The “TypeMismatch” exception occurs when the data types of input and output are not alike. For example, the Math.max() function calculates the maximum of two values and returns a double value. The double value cannot be stored in the integer variable which results in the “TypeMismatch” exception:
public class FindMaxValue {
public static void main(String[] args) {
int number1 = 25;
double number2 = 98.1;
int max=Math.max(number1,number2);
System.out.println("The maximum value is " + max);
}
}
Exception Output
Solution
Typecasting is the conversion of a datatype of a value (int, float, long) to another datatype. We have manually performed typecasting in the code given below. It converts the double value returned by the Math.max() function into an integer value which is stored in the integer “max” variable:
public class FindMaxValue {
public static void main(String[] args) {
int number1 = 25;
double number2 = 98.1;
int max= (int) Math.max(number1,number2);
System.out.println("The maximum value is " + max);
}
}
Output
Exception 2: Method not Applicable
The following exception occurs when a string is passed to the Math.max() function for calculating the highest value. It violates the syntax of the max() method which results in the following exception:
Solution: This exception can be resolved by providing the numeric values of data type int, float, long, or double to the Math.max() method.
Conclusion
The Math.max() is a built-in static method in Java that calculates and returns the maximum value from the two given numeric values. The data type of the output returned depends on the input (values) provided to the method. There are no specific exceptions thrown by this method. However, the invalid input provided or the output conversion can result in the two exceptions discussed in this article. In this article, we have discussed various use cases of using the Math.max() method in Java.