Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Java

Java ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

· 9 min read

Your loop prints every score in the array, and then the program crashes on the very last step:

Terminal
72
85
90
64
88
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
	at Main.main(Main.java:5)

ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 means you asked for position 5 of an array that has 5 elements. That sounds fine, but in Java the positions of an array with 5 elements are 0, 1, 2, 3 and 4. There is no position 5. The message gives you both numbers you need: the index you asked for, and the length of the array. This article shows how to use them, and the five situations where this error usually comes from.

Try it yourself

Save this as Main.java, then run javac Main.java and java Main:

Main.java
public class Main {
    public static void main(String[] args) {
        int[] scores = {72, 85, 90, 64, 88};
        for (int i = 0; i <= scores.length; i++) {
            System.out.println(scores[i]);
        }
    }
}

The program compiles without complaint. The problem appears only when it runs: you'll see the five scores and then the error above.

What the error means

Read it in parts:

  • Exception in thread "main": an exception, a problem while the program was running. Not a compile error: javac had nothing to complain about.
  • java.lang.ArrayIndexOutOfBoundsException: the kind of problem. You used an array index (a position) outside its bounds (the valid range).
  • Index 5: the position you asked for.
  • out of bounds for length 5: how many elements the array really has.
  • at Main.main(Main.java:5): the line in your code where it happened.

The rule that makes it click: array indexes start at 0, so the last valid index is always length - 1. For length 5, valid indexes are 0 to 4. Whenever the two numbers in the message are equal, you've gone exactly one step too far.

Cause 1: <= instead of < in a loop

The example above. The loop condition i <= scores.length lets i reach 5. The fix is one character:

java
for (int i = 0; i < scores.length; i++) {
    System.out.println(scores[i]);
}

With <, i goes 0, 1, 2, 3, 4 and the loop stops. This is the standard shape of a Java loop over an array, and it's worth typing exactly this way every time: start at 0, continue while i < length.

If you only need the values and not the positions, the for-each loop avoids indexes completely:

java
for (int s : scores) {
    System.out.print(s + " ");
}
Terminal
72 85 90 64 88 

No index, so no way to go out of bounds.

Cause 2: asking for the last element with length

To get the last element, it's tempting to write scores[scores.length]:

java
int[] scores = {72, 85, 90};
int last = scores[scores.length];
Terminal
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at Main.main(Main.java:4)

The length is 3, so the last index is 2. Subtract one:

java
int last = scores[scores.length - 1];

Cause 3: counting from 1 instead of 0

People count from 1: day 1 to day 5, question 1 to question 10. Arrays count from 0. When you use a "human" number directly as an index, the last one is out of bounds:

java
int[] counts = new int[5];   // one counter for each of days 1 to 5
int day = 5;
counts[day]++;
Terminal
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
	at Main.main(Main.java:5)

Convert from human numbering to array numbering by subtracting 1:

java
counts[day - 1]++;
System.out.println(java.util.Arrays.toString(counts));
Terminal
[0, 0, 0, 0, 1]

Day 5 is now stored at index 4, the last position. (Making the array one bigger and never using index 0 also works, but later readers may not know why the array is bigger.)

Cause 4: comparing with the next element

A loop that looks at nums[i + 1] goes out of bounds one step earlier than you'd expect:

java
int[] nums = {1, 2, 3, 4};
for (int i = 0; i < nums.length; i++) {
    if (nums[i] < nums[i + 1]) System.out.println("up");
}
Terminal
up
up
up
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
	at Main.main(Main.java:5)

When i is 3, the last valid index, i + 1 is 4. Stop the loop one step earlier: i < nums.length - 1.

Cause 5: an empty array, length 0

When the length in the message is 0, the array has no elements at all, so even index 0 fails:

Terminal
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
	at Main.main(Main.java:4)

Three common sources of an empty array:

  • args with no arguments. args[0] in main fails if you run java Main without anything after it. Check args.length > 0 first.
  • split that found nothing to split. "Sam".split(",") gives an array with one element, "Sam", so parts[1] fails with Index 1 out of bounds for length 1.
  • An array created with a size from a variable that happened to be 0.

Before reading [0] from an array that comes from outside your code, check its length.

A negative index: Index -1

Terminal
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
	at Main.main(Main.java:5)

Negative indexes are never valid in Java (unlike Python, where -1 means the last element). A -1 usually comes from a search that found nothing, like indexOf, which returns -1 when the item isn't there. Check the result before you use it as an index.

The same error with lists and strings

Lists and strings have their own versions of this exception, with the same numbers and the same reasoning:

Terminal
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
	...
	at java.base/java.util.ArrayList.get(ArrayList.java:427)
	at Main.main(Main.java:6)

That's names.get(1) on an ArrayList with one element. The stack trace is longer because the check happens inside Java's own code. Skip the java.base lines and find the first line with your file name: Main.java:6. (We shortened the middle lines here.)

For a String, word.charAt(4) on "Java" gives:

Terminal
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Index 4 out of bounds for length 4

"Java" has 4 characters, at positions 0 to 3.

In older Java versions

Java 8 and earlier printed a shorter message with only the index, for example java.lang.ArrayIndexOutOfBoundsException: 5. Newer versions add the length, which makes the problem much easier to see. If an answer you find online shows the short form, it's the same error.

Errors that look alike

Wrong fixes that don't help

  • Making the array bigger to be safe. The loop still goes one step too far; you'll read a 0 that isn't real data.
  • Catching the exception and ignoring it. The loop's logic stays wrong, and the next change to the array breaks it again.
  • Starting the loop at 1. It removes the error and silently skips the first element.

A debugging walkthrough

A grade program crashes with Index 10 out of bounds for length 10:

  1. Compare the two numbers. Equal? The index is one too high: look for <= or a missing - 1.
  2. Go to the line in the last at Main... line.
  3. Find where the index comes from: a loop counter, a calculation, user input?
  4. For a loop, check the condition: it should be i < array.length.
  5. For a calculation, check whether it uses human numbering (from 1) and needs - 1.
  6. For user input, check the range before using it: if (n >= 0 && n < array.length).

Practice

Predict the message, or the output.

  1. int[] a = new int[3]; a[3] = 1;
  2. String[] parts = "a,b".split(","); System.out.println(parts[parts.length - 1]);
  3. int[] a = {5, 6, 7}; for (int i = 1; i <= a.length; i++) System.out.println(a[i]);

Answers. (1) Index 3 out of bounds for length 3. (2) Prints b: the last index is length - 1. (3) Prints 6 and 7, then Index 3 out of bounds for length 3: the loop skips the first element and goes one step too far.

Frequently asked questions

What does "Index 5 out of bounds for length 5" mean?

You used index 5 on an array with 5 elements. Valid indexes are 0 to 4, so index 5 is one past the end.

Why do Java arrays start at 0?

The index is the distance from the start of the array. The first element is 0 steps from the start. Most programming languages work this way.

How do I get the last element of an array in Java?

array[array.length - 1]. Check first that the array isn't empty.

Is ArrayIndexOutOfBoundsException a compile error?

No. It's a runtime exception: the program compiles and crashes while running, when it actually reaches the bad index.

What's the difference between ArrayIndexOutOfBoundsException and IndexOutOfBoundsException?

The first is for arrays, the second for lists like ArrayList. Strings have StringIndexOutOfBoundsException. The cause and the fix are the same.

A quick checklist

  1. Compare the index and the length in the message.
  2. Equal? Look for <= in a loop or a missing - 1.
  3. Length 0? The array is empty: check before reading [0].
  4. Index -1? Check search results before using them.
  5. Prefer for (int x : array) when you don't need the index.

For a method that works on any error, read how to read an error message. The Java tutorial on arrays explains indexes from the start.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Java

Java error: missing return statement, and how to fix it

Why Java says error: missing return statement when your method clearly returns: if without else, a loop that may not return, try/catch and switch. With compiled examples and fixes.

Error explained · · 9 min read

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right