java program to insert an element at specific position in an array code example

Example 1: java insert array

// ! IMPORTANTE !
// in JAVA an array is not the same as an ArrayList object!!
// 1 - declare, instanciate and populate
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
// 2 - declare and instanciate an int array with maxSize
// note: the index goes between 0 and maxSize-1
int newarr[] = new int[maxSize];
// 2.1 - insert the value n on the position pos
newarr[pos] = n; 
// 2.2 - insert values recursively
for (i = 0; i < maxSize; i++) { newarr[i] = arr[i]; }

Example 2: Java program to insert an element at specific position in an 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();
   }
}

Tags:

Java Example