Java Program to delete an element in an array


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


List is: 2 3 5 7 9 11 13

Delete element is: 13

After delete list is: 2 3 5 7 9 11


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

Run it Now
import java.util.Scanner;

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

        int i, n, num, p = 0;
        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 Delete :");
        num = sc.nextInt();

        for (i = 0; i < n; i++) {
            if (arr[i] == num) {
                arr[i] = arr[i + 1];
                p = 1;
            } else if (p > 0) {
                arr[i] = arr[i + 1];
            }
        }

        System.out.print("\nNew Array List is :");
        for (i = 0; i < n - p; i++) {
            System.out.print(" " + arr[i]);
        }

    }
}

Output:

Enter Size of an Array :5
Enter Array Elements :10 20 30 40 50
Enter Element for Delete :20
New Array List is : 10 30 40 50