ArrayIndexOutOfBoundsException:
In Java,
When we try to access an array element at an index that is outside the array’s bounds, we get the ArrayIndexOutOfBoundsException exception. This indicates that the index being read is either equal to, larger than, or negative than the array’s size.
Example:
public class fileReader{
public static void main (String[] args){
int []number= {1,5,7,9};
try {
System.out.println(number[4]);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(e.getMessage());
System.out.println("Array index out of bound");
}
}//main
}//class
Output:
Index 4 out of bounds for length 4
Array index out of bound
StringIndexOutOfBoundsException:
In Java, A runtime issue known as StringIndexOutOfBoundsException occurs when you attempt to access a character in a String at an incorrect index. This exception is thrown when a character is attempted to be accessed at an index that is either negative or outside the String’s length range.
Example:
public class fileReader{
public static void main (String[] args){
//Index number starts from 0 in String and Array.
0123
String letters = "ABCD";
try {
System.out.println( letters.charAt(4) );
}
catch (StringIndexOutOfBoundsException m) {
System.out.println(m.getMessage());
System.out.println("you string index number is out of bound");
}
}//main
}//class
Output:
String index out of range: 4