Array Index Out Of Bounds Exception in Java
Last Updated :
03 Dec, 2024
In Java, ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program. It occurs when we try to access the element out of the index we are allowed to, i.e. index >= size of the array.
Java supports the creation and manipulation of arrays as a data structure. The index of an array is an integer value that has a 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 Java throws an ArrayIndexOutOfBounds Exception. This is unlike C/C++, where no index of the bound check is done.
Example 1: Here, we are trying to access the index which is greater than or equal to the array length.
Java
// Java program to show ArrayIndexOutOfBoundsException
// when the index is greater than or equal to array length
public class GFG {
public static void main(String[] args)
{
// taking array of integers
int a[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i <= a.length; i++)
System.out.println(a[i]);
}
}
Runtime Error Throws an Exception:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at GFG.main(GFG.java:11)
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.
Example 2: Here, we are trying to access the index of array which is negative.
Java
// Java program to show ArrayIndexOutOfBoundsException
// when we access the negative index of array
public class GFG {
public static void main(String[] args)
{
// taking array of integers
int a[] = { 1, 2, 3 };
// accessing the negative index of array
System.out.println(a[-2]);
}
}
Run-Time Exception:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index -2 out of bounds for length 3
at GFG.main(GFG.java:12)
Handling ArrayIndexOutOfBoundsException in Java
To handle ArrayIndexOutOfBoundsException, make sure that index of array is within the valid range. You can also use the enhanced for-loop to automatically handle this exception.
Example 1: Here, we are checking whether the index is valid or not by taking array length with in the index range i.e. [0, n-1]
Java
// Java program to handle ArrayIndexOutOfBoundsException
// by taking array index within valid range
public class GFG {
public static void main(String[] args)
{
// taking array of integers
int a[] = { 1, 2, 3, 4, 5 };
// here, we have remove equal to sign
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}
Example 2: Here, we are using enhanced for loop that automatically handles the accessing of array’s index
Java
// Java program to handle ArrayIndexOutOfBoundsException
// by using enhanced for loop
public class GFG {
public static void main(String[] args)
{
// taking array of integers
int a[] = { 1, 2, 3, 4, 5 };
// using enhanced for loop
for (int e : a) {
System.out.println(e);
}
}
}
Example 3: 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
// Java program to handle ArrayIndexOutOfBoundsException
// by using using try-catch block
public class GFG {
public static void main(String[] args)
{
// taking array of integers
int a[] = { 1, 2, 3, 4, 5 };
// using try catch block
try {
for (int i = 0; i <= a.length; i++)
System.out.print(a[i] + " ");
}
catch (Exception e) {
System.out.println("\nException Caught");
}
}
}
Output1 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 a[5], the program threw an exception which is caught by the catch block, and it printed the “Exception Caught” statement.
Similar Reads
Errors V/s Exceptions In Java
In Java, errors and exceptions are both types of throwable objects, but they represent different types of problems that can occur during the execution of a program. Errors are usually caused by serious problems that are outside the control of the program, such as running out of memory or a system cr
5 min read
ArrayStoreException in Java
ArrayStoreException in Java occurs whenever an attempt is made to store the wrong type of object into an array of objects. The ArrayStoreException is a class which extends RuntimeException, which means that it is an exception thrown at the runtime. Class Hierarchy: java.lang.Object ↳ java.lang
2 min read
Conversion of Array To ArrayList in Java
Following methods can be used for converting Array To ArrayList: Method 1: Using Arrays.asList() method Syntax: public static List asList(T... a) // Returns a fixed-size List as of size of given array. // Element Type of List is of same as type of array element type. // It returns an List containing
5 min read
Built-in Exceptions in Java with examples
Types of Exceptions in Java Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java. Examples of Built-in Exception: 1. Arithmetic exception : It is thro
8 min read
How to Get Last Element in Array in Java?
In Java, to get the last element in an array, we can access the element at the index array.length - 1 using array indexing. The length property of the array provides its total size, and subtracting one from it gives the index of the last element. Example 1: Here, we will access the last element in a
2 min read
Types of Exception in Java with Examples
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situati
8 min read
Nested try blocks in Exception Handling in Java
In Java, we can use a try block within another try block. This is called nested try blocks. Each time a try statement is entered, the context of that exception is pushed onto a stack. If an exception occurs in the inner try block and is not caught by its corresponding catch block, the exception prop
4 min read
How to Get First Element in Array in Java?
In Java, to get the first element in an array, we can access the element at index 0 using array indexing. Example 1: Below is a simple example that demonstrates how to access the element at index 0 in an array. [GFGTABS] Java public class Geeks { public static void main(String[] args) { // Declare a
2 min read
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 progr
2 min read
Top 5 Exceptions in Java with Examples
An unexpected unwanted event that disturbs the program's normal execution after getting compiled while running is called an exception. In order to deal with such abrupt execution of the program, exception handling is the expected termination of the program. Illustration: Considering a real-life exa
5 min read