Loading
Insertion-tutorial
In Java, arrays are of fixed size, so inserting an element at a specific position involves shifting elements manually to make space for the new item.
This is a common operation when learning array manipulation in Java.



Insertion of element into an array at a specified position

package QuipoHouse.ArrayOperations;

import java.util.Scanner;

public class Insertion {
    public static void main(String[] args) {
        int arr[] = new int[20];  // Declaring array with max size
        int i;

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number of elements (less than 20):");
        int n = sc.nextInt();  // Size of array (n elements)

        System.out.println("Enter the elements of the array:");
        for (i = 0; i < n; i++) {
            arr[i] = sc.nextInt();  // Taking input
        }

        System.out.println("Enter the element to insert:");
        int data = sc.nextInt();

        System.out.println("Enter the position to insert the element:");
        int pos = sc.nextInt();

        // Shift elements to the right from the given position
        for (i = n - 1; i >= pos - 1; i--) {
            arr[i + 1] = arr[i];
        }

        arr[pos - 1] = data;  // Insert the element
        n++;  // Increase array size

        System.out.println("--- Array after Insertion ---");
        for (i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Output:

Enter the number of elements (less than 20):
6
Enter the elements of the array:
1
2
3
4
5
6
Enter the element to insert:
10
Enter the position to insert the element:
5
// --- Array after Insertion ---
1 2 3 4 10 5 6

Explanation

StepDescription
arr[ ] = new int[20];Declares an array with a maximum size of 20
n = sc.nextInt();Reads the number of elements to store initially
arr[i] = sc.nextInt();Stores user inputs into the array
for (i = n-1; i >= pos-1; i--)Shifts elements to the right from the specified position
arr[pos-1] = data;Inserts the new value at the desired position

Tips

  • Java arrays are not resizable, so we manually shift data to perform insertion.
  • Always check array bounds to avoid ArrayIndexOutOfBoundsException.
  • Prefer ArrayList if you need dynamic resizing.