ArrayIndexOutOfBoundsException Vs IndexOutOfBoundsException in Java?

Java 8Object Oriented ProgrammingProgramming

IndexOutOfBoundsException

This type of exception is thrown when you access the element at an index of a type (String, array, collection) beyond its range. It is the super class of ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException.

ArrayIndexOutOfBoundsException

An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation.

The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on.

You can create an array using the new keyword similar to objects and populate it using the indices or, you can directly assign values with in flower braces separating them with commas (,) as −

int myArray[] = new int[7];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;
int myArray = {1254, 1458, 5687, 1457, 4554, 5445, 7524};

Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets.

System.out.println(myArray[3]);
//prints 1457

Generally, an array is of fixed size and each element is accessed using the indices. For example, we have created an array with size 7. Then the valid expressions to access the elements of this array will be a[0] to a[6] (length-1).

Whenever, you used an –ve value or, the value greater than or equal to the size of the array, then the ArrayIndexOutOfBoundsException is thrown.

For Example, if you execute the following code, it displays the elements in the array asks you to give the index to select an element. Since the size of the array is 7, the valid index will be 0 to 6.

Example

import java.util.Arrays;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String args[]){
      int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};
      System.out.println("Elements in the array are: ");
      System.out.println(Arrays.toString(myArray));
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the index of the required element: ");
      int element = sc.nextInt();
      System.out.println("Element in the given index is :: "+myArray[element]);
   }
}

But if you observe the below output we have requested the element with the index 9 since it is an invalid index an ArrayIndexOutOfBoundsException raised and the execution terminated.

Run time exception

Elements in the array are:
[897, 56, 78, 90, 12, 123, 75]
Enter the index of the required element:
7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at AIOBSample.main(AIOBSample.java:12)

StringIndexOutOfBoundsException

Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.

You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).

String stringObject = new String("Hello how are you");
String stringLiteral = "Welcome to Tutorialspoint";

Since the string stores an array of characters, just like arrays the position of each character is represented by an index (starting from 0). For example, if we have created a String as −

String str = "Hello";

The characters in it are positioned as −

If you try to access the character of a String at the index which is greater than its length a StringIndexOutOfBoundsException is thrown.

Example

The String class in Java provides various methods to manipulate Strings. You can find the character at a particular index using the charAt() method of this class.

This method accepts an integer value specifying the index of theStringand returns the character in the String at the specified index.

In the following Java program, we are creating a String of length 17 and trying to print the element at the index 40.

public class Test {
   public static void main(String[] args) {
      String str = "Hello how are you";
      System.out.println("Length of the String: "+str.length());
      for(int i=0; i<str.length(); i++) {
         System.out.println(str.charAt(i));
      }
      //Accessing element at greater than the length of the String
      System.out.println(str.charAt(40));
   }
}

Run time exception

Since we are accessing the element at the index greater than its length StringIndexOutOfBoundsException is thrown.

Length of the String: 17
H
e
l
l
o

h
o
w

a
r
e

y
o
u
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 40
at java.base/java.lang.StringLatin1.charAt(Unknown Source)
at java.base/java.lang.String.charAt(Unknown Source)
at Test.main(Test.java:9)
raja
Updated on 02-Jul-2020 12:42:27

Advertisements