What happens if try to access an element with an index greater than the size of the array in java

What happens if try to access an element with an index greater than the size of the array in java
Educative Answers Team

RELATED TAGS

out of bounds

exception

java

array

Copyright ©2022 Educative, Inc. All rights reserved

Although there are simple cases like your where compilers and/or static analyzers could detect that an access is out of bounds, doing it in general at compile-time is not doable. For example, if you pass off your array to a function it immediately decays into a pointer and the compiler has no chance to do bounds checking at compile-time.

The alternative, run-time bounds checking, is comparatively expensive: doing a check upon each access would turn a simple memory dereference into a potentially stalling branch. To make things even harder, you can use the dereference operator on pointers, i.e., you can't even know easily where to locate the size of the actual array object.

As a result, the behavior of out of bounds array accesses is deliberately made undefined: a system can track these accesses but it doesn't have to. Also, what the system actually does upon an out of bounds array access is not specified, i.e., it can do different things depending on the context. In many cases, it will just return junk which isn't really too useful. However, especially with suitable debug settings the system may instead assert() upon detecting a violation.

Improve Article

Save Article

Like Article

Concept: Arrays are static data structures and do not grow automatically with an increasing number of elements. With arrays, it is important to specify the array size at the time of the declaration. In Java, when we try to access an array index beyond the range of the array it throws an ArrayIndexOutOfBounds Exception. An exception is an obstruction to the normal program execution. Java has try-catch-finally blocks for efficient Exception Handling. ArrayIndexOutOfBoundsException is a runtime exception and must be handled carefully to prevent abrupt termination of the program. 

Approaches:

  1. Using try-catch block where input is taken beyond the array index range
  2. Using try-catch block where input is taken within the array index range
  3. Using constraints over user input 

First Approach

In the first approach, an array of size = 5 is declared. The input is taken within a try block and the loop is executed 6 times. Since the array size is 5, after the 6th input an ArrayIndexOutOfBoundsException is thrown. The exception is handled by the catch block. The code to handle the exception is placed within the catch block. In this example, we notify the user that an exception has occurred and the input exceeds the array range.

Implementation: In all approaches variable named ‘i’ is used of integer data-type been taken for consideration.

import java.util.*;

public class GFG {

    public static void main(String args[])

        throws ArrayIndexOutOfBoundsException

    {

        Scanner s = new Scanner(System.in);

        int arr[] = new int[5];

        try {

            for (int i = 0; i < 6; i++) {

                arr[i] = s.nextInt();

            }

        }

        catch (ArrayIndexOutOfBoundsException e) {

            System.out.println(

                "Array Bounds Exceeded...\nTry Again");

        }

    }

}

Output:

What happens if try to access an element with an index greater than the size of the array in java

Second Approach

In the second approach, we declare an array of size = 5. The input is taken within a while loop inside a try block. The value of i is checked against the size of the array at every iteration. The value of ‘i’ is initiated with 0 and can take input up to index 4. As soon as the value of ‘i’ reaches 5 an exception is thrown. This exception is handled by the catch block. This method is similar to the first one, however, in this approach, no input is taken beyond the array index range which was not the case in the first approach.

Implementation:

import java.util.*;

public class GFG {

    public static void main(String args[])

        throws ArrayIndexOutOfBoundsException

    {

        Scanner s = new Scanner(System.in);

        int arr[] = new int[5];

        / variable created and initialized with 0 int i = 0;

        try {

            while (true) {

                if (i == 5)

                    throw new ArrayIndexOutOfBoundsException();

                arr[i++] = s.nextInt();

            }

        }

        catch (ArrayIndexOutOfBoundsException e) {

            System.out.println(

                "Array Bounds Exceeded...\nTry Again");

        }

    }

}

Output:

What happens if try to access an element with an index greater than the size of the array in java

Third Approach

In this approach we do not use the concept of exception handling rather we limit the input using loops. It is an easier and convenient method of checking array bounds while taking inputs from the user.

Implementation:

import java.util.*;

public class GFG {

    public static void main(String args[])

    {

        Scanner s = new Scanner(System.in);

        int arr[] = new int[5];

        int i = 0;

        while (i < 5) {

            arr[i++] = s.nextInt();

        }

        System.out.println(

            "Array elements are as follows: ");

        for (int j = 0; j < 5; j++)

            System.out.print(arr[j] + "  ");

    }

}

Output:

What happens if try to access an element with an index greater than the size of the array in java