asked 101k views
4 votes
What happens if an array index is out of range in Java?

a) A NullPointerException is thrown
b) A ClassCastException is thrown
c) An IndexOutOfBoundsException is thrown
d) A StackOverflowError is thrown

asked
User Gdoron
by
8.4k points

1 Answer

6 votes

Final answer:

In Java, accessing an array with an index that is out of range will result in an IndexOutOfBoundsException. This occurs if the index is less than 0 or greater than or equal to the array's size and informs that the index used is not valid for the specified array.

Step-by-step explanation:

When an array index is out of range in Java, option c) An IndexOutOfBoundsException is thrown. This is a runtime exception that occurs whenever an attempt is made to access an array element with an index that is outside the bounds of the array (i.e., the index is less than 0 or greater than or equal to the size of the array).

For example, consider an array arr of size 5, where indexes will range from 0 to 4. If you attempt to access arr[5] or arr[-1], Java throws an IndexOutOfBoundsException, precisely an ArrayIndexOutOfBoundsException, to indicate that the index is not valid for the array in question.

No other exceptions such as NullPointerException, ClassCastException, or StackOverflowError are thrown for out-of-bounds array indexes. These exceptions are thrown in different situations unrelated to accessing arrays with an invalid index.

answered
User Jolson Da Costa
by
7.9k points
Welcome to Qamnty — a place to ask, share, and grow together. Join our community and get real answers from real people.