Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

ArrayIndexOutOfBoundsException in Java — Fix (2026) | Tutorials Logic

What is This Error?

The ArrayIndexOutOfBoundsException is thrown when you try to access an array element using an index that is either negative or greater than or equal to the array's length. Java arrays are zero-indexed, so valid indices are 0 to array.length - 1.

Common Causes

  • Using array.length instead of array.length - 1 as the last index
  • Off-by-one error in loop conditions
  • Accessing a negative index
  • Hardcoded index that doesn't match array size
  • Empty array with index access

Quick Fix (TL;DR)

Quick Solution
int[] arr = {10, 20, 30, 40, 50}; // length = 5

// ❌ Problem — index 5 doesn't exist
System.out.println(arr[5]); // Valid: 0-4 only!

// ✅ Solution — use length - 1 for last element
System.out.println(arr[arr.length - 1]); // 50

// ✅ Always check bounds before accessing
if (index >= 0 && index < arr.length) {
    System.out.println(arr[index]);
}

Common Scenarios & Solutions

Scenario 1: Off-by-One in Loop

Problem
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i <= numbers.length; i++) { // ❌ <= should be <
    System.out.println(numbers[i]); // Fails when i = 5!
}
Solution
int[] numbers = {1, 2, 3, 4, 5};

// ✅ Use < (strictly less than)
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

// ✅ Or use enhanced for loop (no index needed)
for (int num : numbers) {
    System.out.println(num);
}

Scenario 2: Empty Array Access

Problem
int[] arr = new int[0]; // Empty array
System.out.println(arr[0]); // ArrayIndexOutOfBoundsException!
Solution
int[] arr = new int[0];

// ✅ Check length before accessing
if (arr.length > 0) {
    System.out.println(arr[0]);
} else {
    System.out.println("Array is empty");
}

Scenario 3: 2D Array Access

Problem
int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
for (int i = 0; i <= matrix.length; i++) {
    for (int j = 0; j <= matrix[i].length; j++) { // ❌ Both <= wrong!
        System.out.print(matrix[i][j]);
    }
}
Solution
int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
for (int i = 0; i < matrix.length; i++) {       // ✅ <
    for (int j = 0; j < matrix[i].length; j++) { // ✅ <
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

Scenario 4: ArrayList vs Array

Solution
// ✅ Use ArrayList for dynamic sizing
List list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

// Safe access with bounds check
int index = 10;
if (index >= 0 && index < list.size()) {
    System.out.println(list.get(index));
}

// ✅ Use streams for safe operations
OptionalInt first = IntStream.of(1, 2, 3).findFirst();
first.ifPresent(System.out::println);

Best Practices to Avoid This Error

  • Use enhanced for loops - Eliminates index management entirely
  • Always use < not <= in loop conditions - Standard pattern for array iteration
  • Check array length before access - Especially for dynamic data
  • Use ArrayList for dynamic collections - Avoids fixed-size limitations
  • Use Arrays.stream() for safe operations - Functional approach avoids index errors
  • Validate input indices - Check bounds before using user-provided indices
  • Use Collections.unmodifiableList() - Prevents accidental modification

Related Errors

Key Takeaways
  • Java arrays are zero-indexed — valid indices are 0 to array.length - 1
  • Use < (not <=) in loop conditions when iterating over arrays
  • Enhanced for-each loops eliminate index management and prevent this error
  • Always check array length before accessing elements from dynamic data
  • Use ArrayList for dynamic collections that grow and shrink
  • Validate user-provided indices before using them to access arrays

Frequently Asked Questions


Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.