Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
public class Main {
public static void main(String[] args) {
int[] a = {1, 2, 3};
System.out.println(a[3]);
}
}An ArrayIndexOutOfBoundsException is thrown
- Expecting
3: indices start at 0, soa[3]is not the third element but the fourth, and the array has only three. - Expecting a compile error: javac does not check index values; the JVM checks every access at run time and throws.
- Which index does the last element of an array have?
- Why does
for (int i = 0; i <= a.length; i++)fail on its last lap?