What causes a Array Index Out Of Bounds Exception and how do I prevent it?

In this Tutorial, we will discuss another exception handling What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? As we know that exception handling is a property of Objective orientation programming. And ArrayOutOfBoundsException is an exception where the exception occurs when we try to access the index of the array which actually does not exist.

Array exception

What Is Array?

The array is a data structure where the element is tried at the same time types in a single variable at their respective index numbers. All the elements are stored in continuation in memory. So it makes us very easy to access the elements of an array from memory and n number of simpler or data of the same data type can be stored at a single location.

which makes an array a very useful tool as it can store all the elements using a single variable.

Provide array is a non Primitive data type that has a fixed size that we need to declare during the declaration of the array and we can not modify the size of the array easily.

Indexes In Array

Indexes referees to the location or address of the element stored in an array using which we can direct access the elements which are stored at a particular index.

Let’s understand using a simple program;

String[] names = { "tom", "bob", "harry" };

Here in the above program names is an array of string types which means it can only store the string data type and as it has three elements so it has a size of 3 where the index numbers start from zero. So the indexes of these elements will be 0, 1, 2.

Array Out Of Bound

As we discussed how each element in the array have a particular index number. Now imagine a situation when you want to know what element is stored at the location of index number 3.

which apparently does not exist this situation in exception handling is known as arrayOutOfBounds.

Let’s take an example:

String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {

Here we can say the length of the array is 3 but the index numbers which are there are 0, 1, and 2 there is no element at index 3 so when we try to access index 3 it will though an exception which means the execution of the program will be stoped as there there is no index called as 3 exist.

Learn More about ArrayIndexOutOfBoundsException and how do I prevent it. : Index Out Of Bound

And visit JAVA TUTORIALfor more infomation.

Leave a Comment

%d bloggers like this: