ArrayIndexOutOfBound Exception Simplified 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 use the memory block before initializing, there will be unpredictable results.
So all arrays may contain either primitive or non primitives(Objects).Any Array element falls between 0 to its length-1. Checking the access of array for each elements 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 it's bounds or illegal index has been passed to access the Array.
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++)

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 run time.This is an unchecked exception so compiler does not check for the correctness.During Run time the exception has been caught. 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 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.