Java Program to Insert Element in Array at Specified Position

Here you will get java program to insert element in array at specified position.

How it works?

  • First copy all the elements before the position where element is to be inserted in a new array.
  • Now assign the element at given position in the new array.
  • Finally copy all the elements after the position where element is to be inserted in a new array.

We can partially copy elements of one array to another using System.arraycopy() method. Its syntax is given below.

System.arraycopy(source_array, start_index_in_source_array, destination_array, start_index_in_destination_array, number_of_elements_to_copy);

In this program I have used System.arraycopy() method for copying the array elements. You can also do this manually inside loop without using this method.

Java Program to Insert Element in Array at Specified Position

import java.util.Scanner;

public class ArrayInsertion {
	public static void main(String args[]){
		int a[] = {1,5,9,6,10,14}, position, element;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Original Array:");
		for(int i : a) {
			System.out.print(i + " ");
		}
		
		System.out.println("\n\nEnter element to insert:");
		element = sc.nextInt();
		
		System.out.println("Enter position of element:");
		position = sc.nextInt();
		
		int b[] = new int[a.length + 1];
		
		System.arraycopy(a, 0, b, 0, position - 1);
		
		b[position - 1] = element;
		
		System.arraycopy(a, position - 1, b, position, a.length - position + 1);
		
		System.out.println("\nArray After Insertion:");
		for(int i : b) {
			System.out.print(i + " ");
		}
	}
}

Output

Original Array:
1 5 9 6 10 14

Enter element to insert:
4
Enter position of element:
2

Array After Insertion:
1 4 5 9 6 10 14

Leave a Comment

Your email address will not be published. Required fields are marked *