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 the array using nextInt() method of Scanner class and then enters all elements of the array.

Now these user entered elements or input are stored in integer array ‘arrNumbers’ using for loop. In the next step user is asked to enter the position(array index number) where element to be inserted at specific position and this user input is stored in integer variable ‘position’.

In the next step user is asked to enter the element to be inserted and this number is stored in integer variable ‘insert’. Now using for loop number is inserted at specific position.

Finally array in which an element inserted at specific position is printed on the console. 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