Insert Element at Specific Position in Array

Inserting an element at a specific position in a Java array requires creating a new array and rearranging elements, as arrays in Java have a fixed size. This is a common task to understand array manipulation and dynamic data handling.

Here’s how you can insert an element at a specific position in a Java array:

package com.javacodepoint.array;

public class InsertElement {
	
	public static void main(String[] args) {
		int[] arr = { 10, 20, 30, 40, 50 };
		int position = 2; // Position where element should be inserted (0-based index)
		int element = 25; // Element to be inserted

		// Create a new array of size n+1
		int[] newArr = new int[arr.length + 1];

		// Copy elements to the new array
		for (int i = 0; i < newArr.length; i++) {
			if (i < position) {
				newArr[i] = arr[i]; // Copy elements before the position
			} else if (i == position) {
				newArr[i] = element; // Insert new element
			} else {
				newArr[i] = arr[i - 1]; // Copy remaining elements
			}
		}

		// Print the new array
		System.out.println("Array after insertion:");
		for (int num : newArr) {
			System.out.print(num + " ");
		}
	}
}

OUTPUT:

Program Explanation:

Since arrays in Java are of fixed size, inserting an element at a specific position requires creating a new array with a size larger than the original array, and then shifting elements accordingly. The steps are as follows:

  1. Create a new array of size n + 1, where n is the size of the original array.
  2. Copy elements from the original array to the new array up to the insertion index.
  3. Insert the new element at the specified index.
  4. Copy the remaining elements from the original array to the new array.

Java logical programs list


Java Basic Programs

Java String Programs

Java String Array Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

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