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

A new array newArr with one extra slot is created; elements before the target position are copied directly, the new element is placed at the position, and remaining elements are shifted right, demonstrating an insertion operation.

Quick Links to Explore