0

I'm trying to understand why my code causes an ArrayIndexOutOfBoundsException. Can someone explain it to me?

public class Test {
    final static int x[] = new int[5];
    public static void main(String[] args) {
    final int x = new Test().x[5];
    if (x <= 10)
        System.out.println("javachamp");
    }
}
  • 6
    Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it). The accepted answer there explains the issue you're seeing in more depth, but basically - the indexes of your array go: 0, 1, 2, 3, 4, not: 1, 2, 3, 4, 5. So the first element is `x[0]`, and the last is `x[4]`. There's no `x[5]`. – DaveyDaveDave May 14 '19 at 08:29

1 Answers1

1

The problem is that index of the array starts at 0. Given you have set the array size to be 5, the last element of the array is x[4] (and the first element will be x[0])

user27158
  • 297
  • 1
  • 5