首页 > 解决方案 > 为什么这段代码会导致 ArrayIndexOutOfBoundsException?

问题描述

我试图了解为什么我的代码会导致 ArrayIndexOutOfBoundsException。有人可以向我解释吗?

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");
    }
}

标签: javaarraysindexoutofboundsexception

解决方案


问题是数组的索引从 0 开始。给定数组大小为 5,数组的最后一个元素是 x[4](第一个元素是 x[0])


推荐阅读