• 2nd Floor, #7a, High School Road, Secretariat Colony Ambattur, Chennai-600053 (Landmark: SRM School) Tamil Nadu, India
• pro@slogix.in
• +91- 81240 01111

### How to handle ArrayIndexOutOfBoundsException in java?

#### 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:

###### Sample 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]);
}
}

###### Screenshots
• 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: