samedi 15 juin 2019

Why there is no error while executing IF statement in this algorithm?

I was repeating some previously passed Java topics and got curious about how exactly does an algorithm work? This algorithm finds the maximum number in an array of ints and returns its index.

public static int findIndexOfMax(int[] numbers) {
    int index = 0;
    for (int i = 1; i < numbers.length; i++) { //i = 0 doesn't seem to change anything
        if (numbers[i] > numbers[index]) { //numbers[1] doesn't exist and still no errors
            index = i;
        }
    }
    return index;
}

public static void main(String[] args) {

    System.out.println(findIndexOfMax(new int[] {99})); //passing an array with a single element
}

Sounds stupid, but why there is no error occured in IF statement if I pass an array with a single element to the method? There we compare non-existent numbers[1] with another int (since the first iteration is for i=1), but we don't get ArrayIndexOutOfBounds exception. What's the reason of it?

Aucun commentaire:

Enregistrer un commentaire