Java IndexOutOfBoundsException

Introduction

IndexOutOfBoundsException in Java is a runtime exception that occurs when trying to access an index that is out of the valid range for a collection or array. It helps identify errors related to index bounds.

Table of Contents

  1. What is IndexOutOfBoundsException?
  2. Common Causes
  3. Handling IndexOutOfBoundsException
  4. Examples of IndexOutOfBoundsException
  5. Conclusion

1. What is IndexOutOfBoundsException?

IndexOutOfBoundsException is thrown to indicate that an index is out of the permissible range for an array, list, or other indexed collections. It is a subclass of RuntimeException.

2. Common Causes

  • Accessing an array or list with a negative index.
  • Using an index greater than or equal to the size of the collection.
  • Incorrect loop boundaries when iterating over collections.

3. Handling IndexOutOfBoundsException

To handle IndexOutOfBoundsException:

  • Validate index values before accessing elements.
  • Use try-catch blocks to catch exceptions.
  • Ensure proper loop boundaries when iterating.

4. Examples of IndexOutOfBoundsException

Example 1: Accessing an Invalid Index

This example demonstrates handling IndexOutOfBoundsException when accessing an index beyond the array length.

public class InvalidIndexExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};

        try {
            int value = numbers[3]; // Invalid index
            System.out.println("Value: " + value);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Error: Index out of bounds.");
        }
    }
}

Output:

Error: Index out of bounds.

Example 2: Iterating Over a List

Here, we handle IndexOutOfBoundsException when using an incorrect loop boundary.

import java.util.ArrayList;
import java.util.List;

public class ListIterationExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");

        try {
            for (int i = 0; i <= list.size(); i++) { // Incorrect boundary
                System.out.println(list.get(i));
            }
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Error: Index out of bounds during iteration.");
        }
    }
}

Output:

A
B
C
Error: Index out of bounds during iteration.

5. Conclusion

IndexOutOfBoundsException in Java helps prevent errors related to invalid index access in arrays and collections. By validating indices and handling exceptions properly, you can ensure robust and error-free code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top