What is the output of the following Java code?
int[] array = {1, 2, 3};
System.out.println(array[3]);

Understanding ArrayIndexOutOfBoundsException in Java

Java is an object-oriented programming language where arrays play a central role, in particular for storing multiple values of the same type. As is the case with most computer programming languages, Java arrays use zero-based indexing. This means that the first element of the array is accessed with the index [0], the second element with index [1], and so on.

When the Java code int[] array = {1, 2, 3}; System.out.println(array[3]); is executed, it tries to access the fourth element in an array that only contains three elements (the indices 0, 1, 2). There is no array[3] in this case, so Java throws an ArrayIndexOutOfBoundsException.

The ArrayIndexOutOfBoundsException is a Run-time Exception thrown by Java when the code tries to access an array element beyond its size or with a negative index. This exception extends the IndexOutOfBoundsException class, which is a child of the RuntimeException class.

To avoid such exceptions, it's a commonly encouraged best practice to always check the length of the array before trying to access its elements. This can be done using the .length property of the array, which gives the total number of elements in the array. Utilizing a for loop or any other iterative construct to access array elements is also highly recommended since these constructs inherently restrict the index values to the valid range.

For instance, to iterate through our array we should use the following code:

int[] array = {1, 2, 3};
for(int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
}

In this example, since i is always less than array.length, we ensure that we are never attempting to access an index that is out of bounds.

In conclusion, handling arrays correctly is a key part of ensuring the robustness and reliability of your Java programs. The ArrayIndexOutOfBoundsException is an important reminder of the need to validate array sizes and indices in your code.

Do you find this helpful?