Array Index Out of Bounds Exception in Java

Java programs use a variety of collection structures for storing and processing data. The array is one of the most common storage objects in Java applications. Once an array has data in it, Java programs can process the data by accessing individual elements or looping through the entire structure, processing one element at a time. Array Index Out Of Bounds Exceptions occur when an incorrect index value is used in an attempt to access an array element.

  1. Array Access

    • Java programs can access array values using the array variable name and index. The index is represented using a primitive type int value. The following code excerpt demonstrates accessing an array element, writing its value to the output console:

      String[] someStrings = {"Red", "Green", "Blue"};

      System.out.println(someStrings[0]);

      The code first creates the array, instantiating it with three elements, then accesses the first item, which is stored at position zero. Java code can also loop through an array, carrying out processing on each element:

      for(int i=0; i<someStrings.length; i++){

      System.out.println(someStrings[i]);

      }

      In this case the code writes each array element on a separate line.

    Index Values

    • Programmers using arrays need to make sure they only use valid array indexes when accessing elements. The only valid array index values are those between zero and one less than the length of the array. Array indexing starts at zero, so the final position in an array with five elements is at index four. When code accesses array elements using either variable references or explicit values, it will only be successful if the index value used is within the range of the array.

    Exceptions

    • Java exceptions arise when something that is not within normal execution or processing occurs. If a code excerpt attempts to access an array item using an index that is either negative or is beyond the final position in the array, Java will throw an Array Index Out Of Bounds Exception. For example, if a program attempts to read the element at position four in an array with four elements, the exception will be thrown since the final array position is three. This error is common in cases where programs are using loops to process array content.

    Compilation and Runtime

    • The Array Index Out Of Bounds Exception is a common one, but programmers do not become aware of it until runtime. Since it is not a checked exception, the possibility of this error will not prevent a program from compiling and running. For this reason, Java programmers have to construct array access code structures carefully, performing extensive testing to ensure an array will only be accessed with valid index values.

Related Searches

References

Resources

Related Ads

Featured