Java program to insert an element at specific position in an array

Let’s learn java program to insert an element at specific position in an array.

Java program to insert an element at specific position in an array

To insert an element at specific position in an array first user enters size of array and then enters all elements of the array.

Now user is asked to enter element to be inserted and the position where the element to be inserted. In the next step shift all elements in array from that position by one and then insert element.

Here’s the program to insert an element in a specified position in a given array.

import java.util.Scanner;
public class InsertElement
{
   public static void main(String[] args) 
   {
      int number, position, insert;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter number of elements in array: ");
      number = sc.nextInt();
      int[] arrNumbers = new int[number + 1];
      System.out.println("Please enter " + number + " elements: ");
      for(int a = 0; a < number; a++)
      {
         arrNumbers[a] = sc.nextInt();
      }
      System.out.println("Please enter position to insert element: ");
      position = sc.nextInt();
      System.out.println("Please enter element you want to insert: ");
      insert = sc.nextInt();
      for(int a = (number - 1); a >= (position - 1); a--)
      {
         arrNumbers[a + 1] = arrNumbers[a];
      }
      arrNumbers[position - 1] = insert;
      System.out.println("After inserting element: ");
      for(int a = 0; a < number; a++)
      {
         System.out.print(arrNumbers[a] + ",");
      }
      System.out.print(arrNumbers[number]);
      sc.close();
   }
}


Output:

Please enter number of elements in array: 6
Please enter 6 elements:
2
8
8
7
6
9
Please enter position to insert element: 3
Please enter element you want to insert: 1
After inserting element: 2,8,1,8,7,6,9


Also read – do while loop in java