Tuesday, October 2, 2012

IndexOutOfBoundsException Example in Java

IndexOutOfBoundsException occurs whenever the number(index) variable increases the ArraySize limit.

(a)
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class IndexOutOfBoundsException {
    public static void main(String args[]){       
        ArrayList a1 = new ArrayList();
           Employee obj = new Employee();
           a1  = (ArrayList)obj.displayRecord();
           Iterator itr = a1.iterator();
           int variable = 0;
           if(a1.size() > 0)
           {
                System.out.println(a1.size());
               /*
               The Arraysize is 10. that is the total number of records are 10., but the ArrayList 
               length starts from 0 until 9, that is internally the index in (b) class ArrayList                                      displayRecord() {} is from 0  to 9 but when it comes to (a) class for{} loop , the for                            loop is  set from 0 to 10....which means that when the for loop  in class(a) starts at                              0 it would be going to the first record in the ArrayIndex  ---  starting at 0(1st record), 
               and hence when the for loop reaches 9 The ArrayIndex  would have reached its full                       ull              strength of 9 (or 10th record) and when the                   class (a)'s for loop reaches 10, obj=(Employee)a1.get(i); will search for the (11th record !!)
               which is not available and hence will throw an IndexOutOfBoundsException
               */

               for(int i=0;i<=a1.size();i++)
               {   
                   obj=(Employee)a1.get(i);
                   variable = obj.getEmployeeNumber();
                   System.out.println(variable);
               }
           }
    }
}

(b)

import java.util.*;
public class Employee {
 
   private int employeeNumber=1;
   public int getEmployeeNumber()
   {
       return employeeNumber;
   }
   public void setEmployeeNumber(int employeeNumber)
   {
       this.employeeNumber=employeeNumber;
   }   
   public ArrayList displayRecord()
   {
       ArrayList showRecord=new ArrayList();
       /*Array Index for loop starts here*/
       for(int i=1;i<=10;i++)
       {
            Employee empObj=new Employee();
            empObj.setEmployeeNumber(i);
            showRecord.add(empObj);
       }
       return showRecord;        
       /*Array Index for loop ends here*/
    }

 }

Answer
----------
10
1
2
3
4
5
6
7
8
9
10
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
    at java.util.ArrayList.rangeCheck(ArrayList.java:604)
    at java.util.ArrayList.get(ArrayList.java:382)
    at pack1.IndexOutOfBoundsException.main(IndexOutOfBoundsException.java:19)

No comments:

Post a Comment