0Pricing
Java Academy · Lesson

Insert, Delete by Index & Shift

Insert into a new array, delete by index with left shift, and practice safe bounds checks.

Insert Overview

Insert into a plain array usually creates a new array with one extra slot. Copy elements before the position, place the new value, then copy the rest shifted by one.

Insert New Array

Insert at index i into a new array:

public class Main {
  // Method to insert a value at a given index
  static int[] insertAt(int[] a, int i, int val) {
    // Create a new array, one element larger
    int[] b = new int[a.length + 1];

    // Copy elements before the insertion index
    for (int p = 0; p < i; p = p + 1) {
      b[p] = a[p];
    }

    // Insert the new value at position i
    b[i] = val;

    // Copy the rest of the elements after position i
    for (int p = i; p < a.length; p = p + 1) {
      b[p + 1] = a[p];
    }

    return b;
  }

  public static void main(String[] args) {
    // Example array
    int[] a = {5, 8, 9, 12};

    // Insert 99 at index 2 (between 8 and 9)
    int[] b = insertAt(a, 2, 99);

    // Print new array
    System.out.print("Array after insertion: ");
    for (int x : b) {
      System.out.print(x + " ");
    }
  }
}

All lessons in this course

  1. Array Basics & Iteration
  2. Searching, Min/Max & Reverse
  3. Insert, Delete by Index & Shift
← Back to Java Academy