java.lang.ArrayIndexOutOfBoundsExcepiton in Java with Examples
The java.lang.ArrayIndexOutOfBoundsException is a runtime exception and thrown only at the execution state of the program. Java compiler never checks for this error during compilation.
The java.lang.ArrayIndexOutOfBoundsException is one of the most common exceptions in java. It occurs when the programmer tries to access the value of an element in an array at an invalid index. This Exception is introduced in Java from JDK Version 1.0 onwards. ArrayIndexOutOfBoundsException can occur due to many reasons like when we try to access the value of an element in the array at a negative index or index greater the size of array -1.
Below are the Code Examples showing the cases in which this error can occur and errors are handled and displayed using try-catch block.
Case 1:- Accessing The Value Of An Element At An Negative Index
The element at index 2 is 2 java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5
Case 2:- Accessing The Element At Index Greater Then Size of Array -1
The element at index 4 is 7 java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.