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

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 Reply

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