Open In App

How to Insert an element at a specific position in an Array in Java

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
18 Likes
Like
Report

An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in Java.
Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos.

Insert Element in specific position in an array

Approach 1: 

Here's how to do it.

  • First get the element to be inserted, say x.
  • Then get the position at which this element is to be inserted, say pos.
  • Create a new array with the size one greater than the previous size.
  • Copy all the elements from previous array into the new array till the position pos.
  • Insert the element x at position pos.
  • Insert the rest of the elements from the previous array into the new array after the pos.

Below is the implementation of the above approach:


Output
Initial Array:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array with 50 inserted at position 5:
[1, 2, 3, 4, 50, 5, 6, 7, 8, 9, 10]

Approach 2: 

Here's how to do it.

  • First get the element to be inserted, say element.
  • Then get the position at which this element is to be inserted, say position.
  • Convert array to ArrayList.
  • Add element at position using list.add(position, element).
  • Convert ArrayList back to array and print.

Below is the implementation of the above approach:


Output
Initial Array:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array with 50 inserted at position 5:
[1, 2, 3, 4, 50, 5, 6, 7, 8, 9, 10]

Article Tags :
Practice Tags :

Similar Reads