Array Index Out Of Bounds Exception in Java - GeeksforGeeks

27 Sep, 2021
Java supports the creation and manipulation of arrays as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the JAVA throws an ArrayIndexOutOfBounds Exception. This is unlike C/C++, where no index of the bound check is done.
The ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program.
Java
// A Common cause index out of boundpublic class NewClass2 {    public static void main(String[] args)    {        int ar[] = { 1, 2, 3, 4, 5 };        for (int i = 0; i <= ar.length; i++)            System.out.println(ar[i]);    }}
Expected Output: 
1
2
3
4
5
Original Output:
Runtime error throws an Exception: 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at NewClass2.main(NewClass2.java:5)
Here if you carefully see, the array is of size 5. Therefore while accessing its element using for loop, the maximum index value can be 4, but in our program, it is going till 5 and thus the exception.
Let’s see another example using ArrayList:
Java
// One more example with index out of boundimport java.util.ArrayList;public class NewClass2{    public static void main(String[] args)    {        ArrayList<String> lis = new ArrayList<>();        lis.add("My");        lis.add("Name");        System.out.println(lis.get(2));    }}
Runtime error here is a bit more informative than the previous time- 
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at NewClass2.main(NewClass2.java:7)
Let us understand it in a bit of detail:
Index here defines the index we are trying to access.
The size gives us information on the size of the list.
Since the size is 2, the last index we can access is (2-1)=1, and thus the exception.
The correct way to access the array is :  
for (int i=0; i<ar.length; i++){

}
Correct Code – 
Java
// Correct code for Example 1public class NewClass2 {    public static void main(String[] args)    {        int ar[] = { 1, 2, 3, 4, 5 };          for (int i = 0; i < ar.length; i++)            System.out.println(ar[i]);    }}
1
2
3
4
5
This automatically handles indices while accessing the elements of an array.
Syntax: 
for(int m : ar){
}
Example:
Java
// Handling exceptions using for-each loopimport java.io.*;  class GFG {    public static void main (String[] args) {                    int arr[] = {1,2,3,4,5};                  for(int num : arr){                            System.out.println(num);                         }    }}
1
2
3
4
5
Consider enclosing your code inside a try-catch statement and manipulate the exception accordingly. As mentioned, Java won’t let you access an invalid index and will definitely throw an ArrayIndexOutOfBoundsException. However, we should be careful inside the block of the catch statement because if we don’t handle the exception appropriately, we may conceal it and thus, create a bug in your application.
Java
// Handling exception using try catch blockpublic class NewClass2 {    public static void main(String[] args)    {        int ar[] = { 1, 2, 3, 4, 5 };        try {            for (int i = 0; i <= ar.length; i++)                System.out.print(ar[i]+" ");        }        catch (Exception e) {            System.out.println("\nException caught");        }    }}
1 2 3 4 5 
Exception caught
Here in the above example, you can see that till index 4 (value 5), the loop printed all the values, but as soon as we tried to access the arr[5], the program threw an exception which is caught by the catch block, and it printed the “Exception caught” statement.
Explore the Quiz Question.
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above.
nishkarshgandhi
Java-Array-Programs
Java-Arrays
Java-Exceptions
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
Set in Java
Collections in Java
Queue Interface In Java
Python Dictionary
Arrays in C/C++
Inheritance in C++
Interfaces in Java
C++ Classes and Objects