Handling ArrayIndexOutOfBoundsException

Description

This program describes how to handle the ArrayIndexOutOfBoundsException exception. This exception arises due to the access of the array element that crosses the size of the array. This problem can be solved by accessing the array index correctly.

  • Exception Handled Code:

  • Filename: Calculation.java

import java.util.*;
class Calculation {
public static void main(String args[]) {
int n[] = new int[5];
n[0] = 20;
n[1] = 40;
n[2] = 60;
n[3] = 10;
n[4] = 30;
int temp;
int i;
for (i= 0; i<5; i++) {
if(n[i] > n[i+1]) {
temp = n[i];
n[i] = n[i+1];
n[i+1] = temp;
}
}
System.out.println("Biggest number is" + n[i]);
}
}

  • Exception Handled Code

import java.util.*;
class Calculation {
public static void main(String args[]) {
int n[] = new int[5];
n[0] = 20;
n[1] = 40;
n[2] = 60;
n[3] = 10;
n[4] = 30;
int temp;
int i;
for (i= 0; i<4; i++) {
if(n[i] > n[i+1]) {
temp = n[i];
n[i] = n[i+1];
n[i+1] = temp;
}
}
System.out.println("Biggest number is" + n[i]);
}
}

Handling ArrayIndexOutOfBoundsException
  • This exception is due to the access of the 5th element in array. But the actual size of the array is 0 to 4 only
  • Exception Handled Code:
Handling ArrayIndexOutOfBoundsException