If statement to check if array is null or empty, doesn't work

Captain Apple :

I got my main task to work (rough translation):

Write a method, which returns the smallest number from a 1d array of integers.

Now i have to do a side task (rough translation):

Add an if statement to check if the array is null or empty, and if it is, return 0.

method:

public static int smallestNumber (int[] array1) {

    int smallest = array1[0];

    if (array1 == null || array1.length == -1) {
       return 0;
    }

    else {
       for (int element : array1) {
          if (element < smallest) {
           smallest = element;
          }
       }
    }
return smallest;    
}

main:

public static void main(String[] args) {
  int[] tab1 = {}; //empty array?
  int smallestNumber = smallestNumber(tab1);
  System.out.printf("The smallest number is: %d", smallestNumber);
}

The method works if i only check for null. But i'm confused why it wont work on empty array.

int[] tab1 = {};

EDIT: I also tried with array1.length == 0;

Fullstack Guy :

Firstly, Arrays are of non-negative size so array1.length cannot be -1, instead make the comparison with 0.

Secondly, the assignment int smallest = array1[0]; tries to access 0th position of an empty array which will result in java.lang.ArrayIndexOutOfBoundsException.

So in conclusion move the assignment to smallest in the else block and check the condition for empty or null array before you try to access any array value.

public static int smallestNumber (int[] array1) {

    int smallest;

    if (array1 == null || array1.length == 0) {
        return 0;
    }

    else {
        smallest = array1[0];
        for (int element : array1) {
            if (element < smallest) {
                smallest = element;
            }
        }
    }
    return smallest;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=89253&siteId=1