Launch your tech mastery with us—your coding journey starts now!
Course Content
Data Structure

Here is a complete Java program demonstrating Insertion and Deletion logic manually. Note that Java’s built-in arrays are fixed, so we simulate insertion/deletion by shifting elements.

import java.util.Scanner;

public class ArrayOperations {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // 1. Creation and Input
        int capacity = 100; // Maximum size buffer
        int[] arr = new int[capacity];
        int n = 0; // Current number of elements

        System.out.print("How many elements initially? ");
        n = sc.nextInt();

        System.out.println("Enter " + n + " elements:");
        for (int i = 0; i = 0 && pos <= n && n  pos; i--) {
                arr[i] = arr[i - 1];
            }

            arr[pos] = val;
            n++;

            System.out.println("Array after Insertion:");
            displayArray(arr, n);

        } else {
            System.out.println("Invalid Position!");
        }

        // 3. DELETION Operation
        // Logic: Shift elements to the left to fill the gap
        System.out.print("\nEnter position to delete (0 to " + (n - 1) + "): ");
        int delPos = sc.nextInt();

        if (delPos >= 0 && delPos < n) {

            for (int i = delPos; i < n - 1; i++) {
                arr[i] = arr[i + 1];
            }

            n--;

            System.out.println("Array after Deletion:");
            displayArray(arr, n);

        } else {
            System.out.println("Invalid Position!");
        }

        sc.close();
    }

    // Helper method to print array
    public static void displayArray(int[] arr, int size) {
        System.out.print("[ ");
        for (int i = 0; i < size; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println("]");
    }
}

Limitations of Arrays

While arrays are fast, they have drawbacks:

  • Fixed Size: You must know the size beforehand. If you need more space, you have to create a new, larger array and copy everything over.
  • Insertion/Deletion Overhead: Removing an element from the beginning requires shifting all other elements, which is slow ($O(n)$).

Solution: For dynamic sizing, Java developers often use ArrayList, which handles resizing automatically.