Java Math max method example shows how to find the maximum of two numbers using the max method of Java Math class.
How to find a maximum of two numbers using Math class?
We can use the max
static method of the Java Math class to find the a maximum of two numbers.
1 |
public static int max(int a, int b) |
This method returns the maximum of two integer numbers.
The max
method has been overloaded for double, float, and long data types so that the same method can be used for double, float, and long types.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.javacodeexamples.mathexamples; public class FindMaxNumberExample { public static void main(String[] args){ int i1 = 10; int i2 = 20; //find maximum of two integer numbers System.out.println( "Maximum Integer number: " + Math.max(i1, i2) ); long l1 = 3421312l; long l2 = 4324212l; //find maximum of two long numbers System.out.println( "Maximum long number: " + Math.max(l1, l2) ); float f1 = 312.321f; float f2 = 231.321f; //find maximum of two float numbers System.out.println( "Maximum float number: " + Math.max(f1, f2) ); double d1 = 234312.32d; double d2 = 321323.31d; //find maximum of two double numbers System.out.println( "Maximum double number: " + Math.max(d1, d2) ); } } |
Output
1 2 3 4 |
Maximum Integer number: 20 Maximum long number: 4324212 Maximum float number: 312.321 Maximum double number: 321323.31 |
How to find the maximum number of 3 or more numbers?
The max
method of Math class accepts only two arguments. So directly, a maximum of 3 numbers cannot be found using the max
method. However, we can find the max of 3 numbers like below given example.
1 2 3 4 5 |
int a = 35; int b = 30; int c = 40; System.out.println( "Max of 3 numbers: " + Math.max( Math.max(a, b), c ) ); |
Output
1 |
Max of 3 numbers: 40 |
This example is a part of the Java Math class tutorial with examples.
Please let me know your views in the comments section below.