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);
}
}
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With