Languages
[Edit]
EN

Java - Math.max() method example

0 points
Created by:
Dirask Admin - Marwin
1430

The Math.max() function returns the highest number from given numbers.

public class MathExample {

    public static void main(String[] args) {
        int max = Math.max(2, 5);
        System.out.println( max ); // 5

        System.out.println( Math.max(1, 2)     ); // 2
        System.out.println( Math.max(1.5, 2.0) ); // 2.0

        System.out.println( Math.max(2, Float.NaN) ); // NaN
    }
}

1. Documentation

Syntax
package java.lang;

public final class Math {

    public static double max(double number1, double number2) { ... }
    public static float max(float number1, float number2) { ... }
    public static int max(int number1, int number2) { ... }
    public static long max(long number1, long number2) { ... }

}

Note: Classes in the java.lang package are imported automatically, so it is not necessary to do it manually - we use just Math.max() call.

Parametersnumber1, number2 - values to compare.
Result

Maximal number value (primitive value).

It returns NaN if at least one of the provided values is not a number.

Descriptionmax is a static method that takes number arguments and returns the biggest one value.

2. Getting max value from array examples

2.1. With Collections.max method example

public class MathExample {
    
    public static void main(String[] args) {
        Integer[] numbersArray = { 1, 5, 2, 16, -5};

        int max = Collections.max(Arrays.asList(numbersArray)); 
        System.out.println( max ); // 16
    }
}

2.2. By comparing all the elements in the array

public class MathExample {

    static double max(double[] array) {
        double result = Double.NEGATIVE_INFINITY;
        for (double currentNumber : array) {
            if (result < currentNumber) result = currentNumber;
        }
        return result;
    }

    public static void main(String[] args) {
        double[] numbersArray = {1.4, 5.0, 2.2, 16.0, -5.0};

        System.out.println(  max(numbersArray) ); // 16.0
    }
}

References

  1. Maxima and minima - Wikipedia

Java - Math object

Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join