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.
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:
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]
- Remove an Element at specific index from an Array in Java
- How to add an element to an Array in Java?
- Find the index of an array element in Java
- Remove all occurrences of an element from Array in Java
- Java Program to find largest element in an array
- First strictly greater element in a sorted array in Java
- First strictly smaller element in a sorted array in Java
- Java Servlet and JDBC Example | Insert data in MySQL
- First element that appears even number of times in an array
- Find closest smaller value for every element in array
- Set to Array in Java
- Array of ArrayList in Java
- Reverse an array in Java
- Array to Stream in Java
- Anonymous array in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.