Which of the following would give you an array index out of bounds exception?

Generally, an array is of fixed size and each element is accessed using the indices. For example, we have created an array with size 9. Then the valid expressions to access the elements of this array will be a[0] to a[8] (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 = {897, 56, 78, 90, 12, 123, 75};
      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.

Output

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)

Handling the exception

You can handle this exception using try catch as shown below.

Example

import java.util.Arrays;
import java.util.Scanner;

public class AIOBSampleHandled {
   public static void main(String args[]) {
      int[] myArray = {897, 56, 78, 90, 12, 123, 75};
      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 ::");
      try {
         int element = sc.nextInt();
         System.out.println("Element in the given index is :: "+myArray[element]);
      } catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("The index you have entered is invalid");
         System.out.println("Please enter an index number between 0 and 6");
      }
   }
}

Output

Elements in the array are::
[897, 56, 78, 90, 12, 123, 75]
Enter the index of the required element ::
7
The index you have entered is invalid
Please enter an index number between 0 and 6

I am having the hardest time trying to fix an ArrayIndexOutOfBoundsException.

I have a method that reads from a file line by line. If the name and id on the line matches some variables that I pass to the method then I save that line to an array.

This program simulates a quiz. The user cannot use the same name and id more than 2 times; therefore, the file only contains 2 lines with the same name and id.

I created an array named temp to hold those two lines from the file. If the file is empty the user takes his two tries and when he tries again it he is denied. So if you enter a different name and id you should get 2 more tries. At this point the file has two lines from the previous user, but when the new user tries he can only take the test once. When he tries the second time I get the array out of bounds exception.

My question is: Is the array temp holding the previous values and is that why I am getting the exception?

private String readFile(String id, String name) {
    String[] temp = new String[3];
    int i = 1;
    int index = 0;
    String[] split = null;
    String idCheck = null;
    String nameCheck = null;
    temp = null;

    try {
        BufferedReader read = new BufferedReader(new FileReader("studentInfo.txt"));
        String line = null;           

        try {
            while ((line = read.readLine()) != null) {
                try {
                    split = line.split("\t\t");
                } catch (Exception ex) {
                }

                nameCheck = split[0];
                idCheck = split[1];

                if (idCheck.equals(id) && nameCheck.equals(name)) {
                    temp[index] = line;
                }

                index++;
            }
            read.close();
        } catch (IOException ex) {
        }
    } catch (FileNotFoundException ex) {
    }

    if (temp != null) {
        if (temp[1] == null) {
            return temp[0];
        }
        if (temp[1] != null && temp[2] == null) {
            return temp[1];
        }
        if (temp[2] != null) {
            return temp[2];
        }
    }

    return null;
}

John Kugelman

341k67 gold badges517 silver badges564 bronze badges

asked Dec 12, 2012 at 19:30

4

I see two places where you can get an index out of bounds exception. First is this code:

try {
    split = line.split("\t\t");
} catch (Exception ex) {
}
nameCheck = split[0];
idCheck = split[1];

If the line does not have a "\t\t" sequence, then split will have only one element and trying to access split[1] will throw an exception. (As an aside: you shouldn't silently ignore exceptions!)

The second (and more likely source of the problem) is that you are incrementing index for every line that has matching id and name, so once you read the third such line, index is out of bounds as a subscript for temp.

You can either include index < temp.length in your while loop condition, or you can use an ArrayList<String> for temp instead of a String[]. That way you can add an unlimited number of strings.

answered Dec 12, 2012 at 19:37

Which of the following would give you an array index out of bounds exception?

Ted HoppTed Hopp

230k48 gold badges392 silver badges519 bronze badges

This is what may be happening

    String[] split = "xxx\tyyyy".split("\t\t");
    System.out.println(split[0]);
    System.out.println(split[1]);

.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at Test.main(Test.java:17)

answered Dec 12, 2012 at 19:36

Evgeniy DorofeevEvgeniy Dorofeev

132k29 gold badges198 silver badges269 bronze badges

After setting temp = null;

The next reference to temp is:

if (idCheck.equals(id) && nameCheck.equals(name)) {

    temp[index] = line;
}

I believe you should remove the line temp = null;. All it does is trash the array you just instantiated above that line.

That index makes me a touch nervous, but I suppose if you are certain that the file being read will never have more than 3 lines...

answered Dec 12, 2012 at 19:43

femtoRgonfemtoRgon

32.6k7 gold badges59 silver badges87 bronze badges

What is array index out of bound exception?

The ArrayIndexOutOfBoundsException is one of the most common errors in Java. It occurs when a program attempts to access an invalid index in an array i.e. an index that is less than 0, or equal to or greater than the length of the array.

Which of the following would be a correct way to handle an index out of bound exception?

Throw the exception and catch it. In the catch, set the index to the index of the arrayclosest to the one that was out of bounds.

How to check if array index is out of bounds Java?

Simply use: boolean inBounds = (index >= 0) && (index < array. length);