Get startedGet started for free

Edge cases: Array maximum

Another common programming exercise is about sorting or finding the maximum value in an array. Here is the simplest version of a it, together with a basic solution. The solution is not entirely correct, as it does not handle a key edge case, an empty array, which will result in an exception.

Run the code to see a RuntimeException triggered.

This exercise is part of the course

Introduction to Testing in Java

View Course

Exercise instructions

  • Click "Run Code" to produce an ArrayIndexOutOfBoundsException and then submit.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

public class MaxValue {

    public static void main(String[] arguments) {
    	// Enter the array elements that cause an ArrayIndexOutOfBoundsException
        System.out.println(findMax(new int[]{}));
    }

    public static int findMax(int[] numbers) {
        int max = numbers[0];
        for (int num : numbers) {
            if (num > max) {
                max = num;
            }
        }
        return max;
    }
}
Edit and Run Code