0

In the second if statement when I'm comparing values[i] and values[secondIdx], why doesn't this cause an error seeing as secondIdx is equal to -1?

public static int getSecondMinIndex(int[] values) {
        int secondIdx = -1;
        int minIdx = getMinIndex(values);
        for (int i = 0; i < values.length; i++) {
            if (i == minIdx)
                continue;
            if (values[i] < values[secondIdx] || secondIdx == -1)
                secondIdx = i;
        }
        return secondIdx;
}
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142

1 Answers1

1

The only ways this would not throw an error at runtime is if you passed an empty array as a method argument, in which case the for loop would not execute. Also, as Bhesh suggests, if the array has one element and the minIdx is that first element at index 0, the loop will execute once, enter the first if and continue. It will stop looping right after that. That would also not cause the exception.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724