Close

Java - Math.max() Examples

Java Java API 


Class:

java.lang.Math

java.lang.Objectjava.lang.Objectjava.lang.Mathjava.lang.MathLogicBig

Methods:

public static int max(int a,
                      int b)

Returns the greater of two int values.



public static long max(long a,
                       long b)

Returns the greater of two long values. T



public static float max(float a,
                        float b)

Returns the greater of two float values.



public static double max(double a,
                         double b)

Returns the greater of two double values.

Examples


package com.logicbig.example.math;

public class MaxExample {

public static void main(String... args) {
findMax(43, 45);
findMax(-31, 5);
findMax(-91, -105);
findMax(Integer.MIN_VALUE, 3);
findMax(3521, Integer.MAX_VALUE);
}

private static void findMax(int a, int b) {
int maxValue = Math.max(a, b);
System.out.printf("Math.max(%s,%s) = %s%n", a, b, maxValue);
}
}

Output

Math.max(43,45) = 45
Math.max(-31,5) = 5
Math.max(-91,-105) = -91
Math.max(-2147483648,3) = 3
Math.max(3521,2147483647) = 2147483647




package com.logicbig.example.math;

public class MaxExample2 {

public static void main(String... args) {
findMax(60994, 9785l);
findMax(-100000L, 200000L);
findMax(-11010010, -1051111);
findMax(Long.MIN_VALUE, -1);
findMax(7896541, Long.MAX_VALUE);
}

private static void findMax(long a, long b) {
long maxValue = Math.max(a, b);
System.out.printf("Math.max(%s,%s) = %s%n", a, b, maxValue);
}
}

Output

Math.max(60994,9785) = 60994
Math.max(-100000,200000) = 200000
Math.max(-11010010,-1051111) = -1051111
Math.max(-9223372036854775808,-1) = -1
Math.max(7896541,9223372036854775807) = 9223372036854775807




package com.logicbig.example.math;

public class MaxExample3 {

public static void main(String... args) {
findMax(90.652f, 90.678f);
findMax(-42.95f, 32.65f);
findMax(-2.22f, -11.111f);
findMax(Float.MIN_VALUE, -1.25f);
findMax(310.25f, Float.MAX_VALUE);
}

private static void findMax(float a, float b) {
float maxValue = Math.max(a, b);
System.out.printf("Math.max(%s,%s) = %s%n", a, b, maxValue);
}
}

Output

Math.max(90.652,90.678) = 90.678
Math.max(-42.95,32.65) = 32.65
Math.max(-2.22,-11.111) = -2.22
Math.max(1.4E-45,-1.25) = 1.4E-45
Math.max(310.25,3.4028235E38) = 3.4028235E38




package com.logicbig.example.math;

import java.util.Arrays;

public class MaxExample4 {

public static void main(String... args) {
double[] values = {123545d, 710129d, 426561d, 354568d};
System.out.println(Arrays.toString(values));
double maxValue = values[0];
for (int i = 1; i < values.length; i++) {
maxValue = Math.max(maxValue, values[i]);
}
System.out.println("The maximum value is : " + maxValue);
}
}

Output

[123545.0, 710129.0, 426561.0, 354568.0]
The maximum value is : 710129.0




See Also