What is ArrayIndexOutOfBoundsException in Java: Explanation and Example
ArrayIndexOutOfBoundsException is an error that happens when you try to access an array element using an index that is outside the valid range (less than 0 or greater than or equal to the array length). It signals that your program is trying to reach a position in the array that does not exist.How It Works
Imagine an array as a row of mailboxes numbered from 0 up to one less than the total number of mailboxes. Each mailbox holds a value. When you want to get or set a value, you tell the program which mailbox number (index) to use.
If you ask for a mailbox number that doesn't exist, like mailbox number 10 when there are only 5 mailboxes, the program doesn't know what to do. Java then throws an ArrayIndexOutOfBoundsException to warn you that the index is invalid.
This exception helps catch mistakes early, so you can fix the code before it causes bigger problems.
Example
This example shows an array of 3 numbers. Trying to access the element at index 3 causes an ArrayIndexOutOfBoundsException because valid indexes are 0, 1, and 2.
public class Main { public static void main(String[] args) { int[] numbers = {10, 20, 30}; System.out.println(numbers[0]); // prints 10 System.out.println(numbers[3]); // causes ArrayIndexOutOfBoundsException } }
When to Use
You don't "use" ArrayIndexOutOfBoundsException on purpose; it is a signal from Java that your code tried to access an invalid array position. You should write your code carefully to avoid this error by always checking that your index is within the array's valid range.
In real-world programs, this exception helps you find bugs related to loops or calculations that go beyond the array size, such as reading user input into an array or processing lists of data.
Key Points
- Array indexes start at 0 and go up to length - 1.
ArrayIndexOutOfBoundsExceptionhappens when you use an index outside this range.- This exception helps catch errors early in your program.
- Always check array length before accessing elements.