Java Program to insert an element in an array


In this program, You will learn how to insert an element in an array in Java.


List is: 2 3 5 7 9 11 13

Insert location: 8

Insert new element is: 33

After insert list is: 2 3 5 7 9 11 13 33


Example: How to insert an element in an array in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int n, i, num, loc;
        int arr[] = new int[100];
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Size of an Array :");
        n = sc.nextInt();

        System.out.print("\nEnter Array Elements :");
        for (i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.print("\nEnter Element for Insert :");
        num = sc.nextInt();

        System.out.print("\nEnter location :");
        loc = sc.nextInt();

        for (i = n; i >= loc; i--) {
            arr[i] = arr[i - 1];
        }
        n++;
        arr[loc - 1] = num;

        System.out.print("\nAll Numbers is :");
        for (i = 0; i < n; i++) {
            System.out.print(" " + arr[i]);
        }

    }
}

Output:

Enter Size of an Array :5
Enter Array Elements :10 20 30 40 50
Enter Element for Insert :15
Enter location :2
All Numbers in Array are : 10 15 20 30 40 50