Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ArrayIndexOutOfBoundsException: 0 - Array larger than Index?

Does the exception thrown indicate that the array is larger than the index? If not, what does it mean, and why? How do I correct it?


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at leapyear.LeapYear.main(LeapYear.java:13)


public class LeapYear {

public static void main(String[] args) { 
    int year = Integer.parseInt(args[0]);
    boolean isLeapYear;

    // divisible by 4
    isLeapYear = (year % 4 == 0);

    // divisible by 4 and not 100
    isLeapYear = isLeapYear && (year % 100 != 0);

    // divisible by 4 and not 100 unless divisible by 400
    isLeapYear = isLeapYear || (year % 400 == 0);

    System.out.println(isLeapYear);
}
}
like image 494
CRNYC Avatar asked Oct 23 '11 22:10

CRNYC


2 Answers

The array doesn't contain any elements--it is an empty array. So when you ask for the first element in the array (the element contained at index 0) the array says "I don't have an element at index 0". It 'says' this by throwing an exception. In your case, the exception is java.lang.ArrayIndexOutOfBoundsException: 0

This means that the index you requested is outside the bounds of the array. In other words, the array has a length (it's bounds). When it's length is 0 (it's empty) and you ask for the 1st element, the array tells you the item you requested is unavailable because the array isn't even 1-element long.

like image 173
BigSauce Avatar answered Sep 28 '22 13:09

BigSauce


It means the array is smaller than the index. In that case it means the array is empty.

You should pass a command-line argument in order to have a value there. And if it is required, you'd better add some validation, like

if (args.length == 0) {
    throw new IllegalArgumentException("year is required");
}
like image 44
Bozho Avatar answered Sep 28 '22 13:09

Bozho