Insert an element (specific position) into an array in Java


This program inserts an element into a specific index of an integer array.

  • The program first declares an integer array a with some initial values.
  • The program then initializes two variables index and value which represent the index at which the new value will be inserted and the value itself, respectively.
  • The program then prints the array before insertion using Arrays.toString(a) and stores the result in a string.
  • The program then uses a for loop to shift all the elements to the right of the specified index one position to the right. The loop starts at the end of the array and iterates backwards until it reaches the specified index. For each iteration, the program sets the current element to be equal to the element to its left.
  • After shifting the elements, the program sets the element at the specified index to the new value.
  • Finally, the program prints the updated array using Arrays.toString(a) and stores the result in a string.

Source Code

import java.util.Arrays;
public class Insert_element_array {
    public static void main(String args[])
    {
        //Program to insert a element in specific index of an array
        int[] a = {10,20,30,40,50,60,70,80,90,100};
        int index = 2;
        int value = 55;
        System.out.println("Before Insert "+Arrays.toString(a) );
 
        for(int i=a.length-1;i>index;i--)
        {
            a[i]=a[i-1];
        }
        a[index]=value;
        System.out.println("After Insert "+Arrays.toString(a) );
    }
}
 

Output

Before Insert [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
After Insert [10, 20, 55, 30, 40, 50, 60, 70, 80, 90]
To download raw file Click Here

Basic Programs