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:
Array after insertion:
10 20 25 30 40 50
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:
- Create a new array of size
n + 1
, wheren
is the size of the original array. - Copy elements from the original array to the new array up to the insertion index.
- Insert the new element at the specified index.
- Copy the remaining elements from the original array to the new array.