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.

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("Enter array elements:");
        for (i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.print("Enter element for insert:");
        num = sc.nextInt();

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

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

        System.out.print("All 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:33
Enter location:4
All numbers is: 10 20 30 33 40 50