SoFunction
Updated on 2025-03-09

Solution to Java index out-of-bounds exception Exception

1. IndexOutOfBoundsException is an index out-of-bounds exception

Indicates that some kind of index (such as an array, string, or vector) is out of range

Example: Please see the following code

 public static void main(String[] args) {
        List<Object> list = new ArrayList();
        ("The first element added python");
        ("Added second element java");
        ("The third element added Javascript");
        ("The fourth element added C++");
        (());   //Print result is: 4        for (int i = 0;i <= ();i++) {
            (((i)));
        }
 }

An error was reported after running:

Exception in thread "main" : Index: 4, Size: 4
Mainly because: the cycle condition is i  <= ()  and then (i) an error is reported

Analysis: If the list adds data to n, because the index starts from 0, the last data should be indexed as n-1. If the index is greater than or equal to n, an out-of-bounds exception is reported:

2. ArrayIndexOutOfBoundsException: Array index out of bounds exception

Indicates that an array was accessed using an illegal index. The index is a negative number or greater than or equal to the size of the array.

  for (int i = 0;i <= ();i++) {
            (((i-1)));
      }

In the above example, (-1) will report an error, so it is easy to find the problem.

This is the end of this article about solving Java index out-of-bound exception Exception. For more related content on Java index out-of-bound exceptions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!