ArrayIndexOutOfBound Exception Simplified in Java

ArrayIndexOutOfBound Exception
ArrayIndexOutOfBound Exception

ArrayIndexOutOfBound Exception in Java:

Before we really look for this class, we need to understand the Array. Click here to understand more about an Array--here.
Arrays are blocks of memory and if a program tries to access the Array that is outside of the memory block(Array), or tries to use the memory block before initializing, there will be unpredictable results.
So all arrays may contain either primitive or nonprimitives (Objects). Any Array element falls between 0 to its length-1. Checking the access of array for each element can be a source of inefficiency of code.

This exception is thrown by java compiler to indicate that the coder may have accessed outside of its bounds or illegal index has been passed to access the Array.
The illegal index could be negative, greater than or equal to the size of the array.
The class looks like the below:

public class java.lang.ArrayIndexOutOfBoundsException extends
// This constructor contructs an ArrayIndexOutOfBoundsException with no message
public ArrayIndexOutOfBoundsException();
//This constructor constructs and ArrayIndexOutOfBoundsException with the message specified
public ArrayIndexOutOfBoundsException(String message);
//This constructor constructs an ArrayIndexOutOfBoundsException with the illegal index
public ArrayIndexOutOfBoundsException(int index); 
Here is an example to show how this exception occurs in java coding:

public class ArrayTest{
public static void main(String[] args)    
int a[]={1,2,3};
for(int i=0;i<=a.length;i++)

the output of the code:
$java -Xmx128M -Xms16M ArrayTest
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at ArrayTest.main(

Notice here: the compiler did compile the code but it failed at runtime. This is an unchecked exception so the compiler does not check for the correctness. During Runtime the exception has been caught. The exception has been thrown as we tried to access an element which is 4(greater than the capacity limit of the array) and outside of the bound. Check the for the loop - it starts with 0 and should go till a.lenth-1
ArrayIndexOutOfBound Exception Simplified in Java ArrayIndexOutOfBound Exception Simplified in Java Reviewed by Animesh Chatterjee on August 27, 2018 Rating: 5

No comments:

Powered by Blogger.