Amazing technological breakthrough possible @S-Logix pro@slogix.in

Office Address

  • #5, First Floor, 4th Street Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 Landmark : Samiyar Madam
  • pro@slogix.in
  • +91- 81240 01111

Social List

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:

Handle ArrayIndexOutOfBoundsException in java
Exception Handled Code