Insert Element in Array
This program inserts an element at a specific position in an array.
Problem Statement
Write a Java program to insert an element at index 2 in an integer array.
Source Code
| 1 | public class ArrayInsertion { |
| 2 | public static void main(String[] args) { |
| 3 | int[] arr = {10, 20, 30, 40, 50}; |
| 4 | int pos = 2, element = 99; |
| 5 | int[] newArr = new int[arr.length+1]; |
| 6 | for(int i=0; i<pos; i++) newArr[i] = arr[i]; |
| 7 | newArr[pos] = element; |
| 8 | for(int i=pos; i<arr.length; i++) newArr[i+1] = arr[i]; |
| 9 | System.out.print("Array after insertion: "); |
| 10 | for(int num : newArr) System.out.print(num + " "); |
| 11 | } |
| 12 | } |
Program Output
Array after insertion: 10 20 99 30 40 50
Explanation
Original array arr initialized. - New array newArr created with one extra space. - Elements before position copied directly. - New element inserted at position. - Remaining elements shifted right. - Together demonstrates insertion operation. Conclusion: Shows how arrays can be manipulated to insert elements.