[java] How to check if an array is empty?

I have written a program where if the array set is let's say {1, 3, 6, 7, 12}, it will return its minimum gap between two numbers. In other words, it will first find the differences between 3 and 1, 6 and 3, 7 and 6, and 12 and 7. After their differences are achieved, it will return the least difference, in our case 1, since 6-7=1. If we were given an array set of {60}, for example, the program will return 0. Now if we had an array set of {}, where nothing is inside, it will return 0 as well. However, I can't get my program to return a 0! It throws an exception. What did I miss? How should I solve this problem? Here is my program so far:

public static void main(String[] args) {
    int[] numberSet = {1, 3, 6, 7, 12};
    //int[] numberSet = {};
    System.out.println(minGap(numberSet));      
}

public static int minGap(int[] numberSet) {
    int[] differenceArray = new int[numberSet.length-1];
    int smallestNum = 0;
    if (numberSet.length < 2) {
        return 0;
    }
    else {
        for(int i = 0; i < numberSet.length-1; i++) {
            differenceArray[i] = numberSet[i+1] - numberSet[i]; 
        }       
        Arrays.sort(differenceArray);
        smallestNum = differenceArray[0];
        return smallestNum;
    }
}

Thanks in advance!

This question is related to java arrays

The answer is


you may use yourArray.length to findout number of elements in an array.

Make sure yourArray is not null before doing yourArray.length, otherwise you will end up with NullPointerException.


Your problem is that you are NOT testing the length of the array until it is too late.

But I just want to point out that the way to solve this problem is to READ THE STACK TRACE.

The exception message will clearly tell you are trying to create an array with length -1, and the trace will tell you exactly which line of your code is doing this. The rest is simple logic ... working back to why the length you are using is -1.


To check array is null:

int arr[] = null;
if (arr == null) {
 System.out.println("array is null");
}

To check array is empty:

arr = new int[0];
if (arr.length == 0) {
 System.out.println("array is empty");
}