Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaArray Index Out Of Bounds Exception in Java

Array Index Out Of Bounds Exception in Java

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 of index out of bound
public 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 bound
import 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 1
public 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]);
    }
}


Output

1
2
3
4
5

Handling the Exception:

1. Using for-each loop: 

This automatically handles indices while accessing the elements of an array.

Syntax: 

for(int m : ar){
}

Example:

Java




// Handling exceptions using for-each loop
import 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);    
           
        }
    }
}


Output

1
2
3
4
5

2. Using Try-Catch: 

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 block
public 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");
        }
    }
}


Output

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 Lazyroar 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 Lazyroar 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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments