javaarraysexceptioninsert

Insert element in array in Java


Why is there an ArrayIndexOutOfBoundsException?

I have tried changing the size of the array but still I am unable to create successful program

import java.util.Scanner;

class insert
{
    
    public static void main(String[]args) throws Exception
    {
        Scanner sc = new Scanner(System.in);
        int a[]= new int[5];
        int i;
        

        for(i=0;i<a.length-1;i++)
        {
            System.out.println("Enter the Element : ");
            a[i]=sc.nextInt();

        }

        System.out.println("Enter the location for insertion : ");
        int loc = sc.nextInt();
        System.out.println("Enter the value for location : " +loc+" is");
        int value = sc.nextInt();

        for(i=a.length-1;i>loc;i--)
        {
            a[i+1]=a[i];
        }
        a[loc-1] = value;
        System.out.println("New Array is : ");

        for (i=0;i<=a.length-1;i++)
        {
            System.out.println(a[i]);
        }
    }
}

Solution

  • In this part:

    for(i=a.length-1;i>loc;i--)
        {
            a[i+1]=a[i];
        }
    

    On the first iteration, a[i+1] is the same as a[a.length], but the last element in array is a[a.length-1], becausefirst element is a[0] and last one is a[length-1], in total a.length number of elements. So modify your loop accordingly.

    One side note, when you define a size of an array, you cannot change it. Size is immutable. So you cannot insert an element and try to shift all the elements, because you need to increase the size with 1, which is not possible. For this scenario, use ArrayList<Integer>>. ArrayList size increases as you add new elements