Wednesday, 7 January 2015

Java java.lang.ArrayIndexOutOfBoundsException Error

If you use an array in your program, you need to be sure that you always access it with a valid subscript:
 
Java > cat prog75.java
public class prog75
{
public static void main (String args[])
  {
  int[] n = new int[5];
  for (int x=0;x<5;x++)
    {
    n[x]=2*x;
    System.out.println("n[" + x + "] = " + n[x]);
    }
  System.out.println("Finished");
  }
}
Java > javac prog75.java
Java > java prog75
n[0] = 0
n[1] = 2
n[2] = 4
n[3] = 6
n[4] = 8
Finished
Java >
 
…otherwise, you will get a run-time error:
 
Java > cat prog76.java
public class prog76
{
public static void main (String args[])
  {
  int[] n = new int[5];
  for (int x=0;x<6;x++)
    {
    n[x]=2*x;
    System.out.println("n[" + x + "] = " + n[x]);
    }
  System.out.println("Finished");
  }
}
Java > javac prog76.java
Java > java prog76
n[0] = 0
n[1] = 2
n[2] = 4
n[3] = 6
n[4] = 8
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
        at prog76.main(prog76.java:8)
Java >