Finding Min and Max from Primitive Array in Java

Many time we need to find minimum and maximum from arrays of primitive types like int, long, float and others in Java. To do this there are several methods we can use like array traversal, using List and Collections classes.

Most efficient method is finding it by comparing arrays elements using loop. Here are 2 functions for finding min and max of integer.

Example for finding minimum from array

    public static int min(int[] array) {
        // Validates input
        if (array == null) {
            throw new IllegalArgumentException("The Array must not be null");
        } else if (array.length == 0) {
            throw new IllegalArgumentException("Array cannot be empty.");
        }
    
        // Finds and returns min
        int min = array[0];
        for (int j = 1; j < array.length; j++) {
            if (array[j] < min) {
                min = array[j];
            }
        }
        return min;
    }

Example for finding maximum from array

    public static int max(int[] array) {
        // Validates input
        if (array == null) {
            throw new IllegalArgumentException("The Array must not be null");
        } else if (array.length == 0) {
            throw new IllegalArgumentException("Array cannot be empty.");
        }
        // Finds and returns max
        int max = array[0];
        for (int j = 1; j < array.length; j++) {
            if (array[j] > max) {
                max = array[j];
            }
        }
        return max;
    }